Reputation:
In this method, I tried to convert decimal numbers to any base. This method works well.
I have used two nested if
statements. There are 7 modes in the internal statement.
My teacher asked me to write all these if
statements in one line.
Is there a way?
I know about the ?:
statement but I have to use just one of these statements.
private string Converting(int a, int b)
{
string result = string.Empty;
int remaining;
// start while loop statement
while (a > 0)
{
remaining = a % b;
// start if else statement to validate value of b
if (b >= 11 && b <= 16)
{
if (remaining == 10)
{
result += 'A';
}
else if (remaining == 11)
{
result += 'B';
}
else if (remaining == 12)
{
result += 'C';
}
else if (remaining == 13)
{
result += 'D';
}
else if (remaining == 14)
{
result += 'E';
}
else if (remaining == 15)
{
result += 'F';
}
else
{
result += remaining;
}
}
else
{
result += remaining;
}
a /= b;
}
return new string(result.ToCharArray().Reverse().ToArray());
}
Upvotes: 0
Views: 88
Reputation: 703
You could convert the remaining to a char:
if (remaining >= 10)
{
result += (char)('A' + remaining - 10);
}
else
{
result += remaining;
}
In a single line:
result += remaining >= 10 ? (char)('A' + remaining - 10) : remaining;
Or extract from a string:
result += "0123456789ABCDEF"[remaining]
Upvotes: 3