I am like 2 weeks new to C# or coding overall and I am trying to figure out the following:
Write a console application that displays for each digit, starting with the most significant, whether it is odd or even.
For input data:
5228
The console will display:
ODD
EVEN
EVEN
EVEN
When running my code I get:
EVEN
EVEN
EVEN
ODD
Can you help me start from the most significant digit?
This is my current implementation:
using System;
public class TestVariablesandExpressions
{
static void Main(string[] args)
{
string inputData = Console.ReadLine();
int num = Convert.ToInt32(inputData);
int reverse = 0;
while (num > 0)
{
reverse = reverse * 10 num % 10;
num /= 10;
if (reverse % 2 == 0)
{
Console.WriteLine("EVEN");
}
else
{
Console.WriteLine("ODD");
}
}
}
}
CodePudding user response:
Sorry, but you can't solve the task with you current reverse implementation: the counter example is when num
ends with 0
:
num == 12000 => (reverse) => 00012 == 12 => "ODD EVEN"
Another problem which is in you current code is a potential integer overflow: no int
value can be greater than int.MaxValue = 2147483647
, but if num
ends with 2..9
the reversed value can exceed the int.MaxValue
:
1000000009 => (reverse) => 9000000001 => (overflow) == 410065409
(or something else depending on reverse implementation)
But you can preserve trailing zeroes and forget about overflow by using string
instead of int
. The only potential problem is negative numbers where we should skip -
(-123 => ODD EVEN ODD
).
int num = ...
string text = num.ToString();
for (int i = 0; i < text.Length; i)
if (text[i] >= '0' && text[i] <= '9') { // In case we have negative numbers
if ((text[i] - '0') % 2 == 0) // Note, that text[i] is char, not int
Console.WriteLine("EVEN");
else
Console.WriteLine("ODD");
}
CodePudding user response:
Modulo operator %
returns the last digit. It would be way easier to handle a string, so you can use foreach
loop over each character, then convert it to an integer in your loop.
First control if the entry is a number, and trim spaces with Convert.ToInt32(inputData).ToString();
(It converts it to a number, then converts the number to a string)
string inputData = Console.ReadLine();
inputData = Convert.ToInt32(inputData).ToString();
foreach (char digit in inputData)
{
if (Convert.ToInt32(digit.ToString()) % 2 == 0)
{
Console.WriteLine("EVEN");
}
else
{
Console.WriteLine("ODD");
}
}
Or shorter :
string inputData = Console.ReadLine();
inputData = Convert.ToInt32(inputData).ToString();
foreach (char digit in inputData)
{
Console.WriteLine(Convert.ToInt32(digit.ToString()) % 2 == 0 ? "EVEN" : "ODD");
}