Hi guys,
I want to know if there is a way in C# to convert an integer
to an array of digits so that I can perform (Mathematical) operations
on each digit alone
ex:
I need the user to input an integer i.e 123 , 456
then the program creates two arrays of three element {1,2,3} , {4,5,6}
then add each digit in one array to its corresponding digit in the second array,
stores the results in a new array
thnx in advance
5 replies to this topic
#1
Posted 20 May 2011 - 07:21 AM
|
|
|
#2
Posted 20 May 2011 - 07:44 AM
Your easiest way of doing this would be to simply accept a string of characters from the user and scan it one character at a time, parsing those characters to Ints as you store them in your array.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid
#3
Posted 20 May 2011 - 08:00 AM
would you please provide an example , because it doesn't work for me
#4
Posted 20 May 2011 - 01:29 PM
Use Console.Read to read characters one by one. You can put this read method call in the conditional of a while loop, and set it to execute the loop only when it is not equal to -1, because Console.Read returns -1 when the input buffer is empty.
You should check the value of this character to make sure it is a digit. You can use Convert.ToChar(i), where i is an Int32, to convert the integer returned by Console.Read to a Character. Then, you can call Char.IsDigit© on that character to make sure it's a digit.
You should check the value of this character to make sure it is a digit. You can use Convert.ToChar(i), where i is an Int32, to convert the integer returned by Console.Read to a Character. Then, you can call Char.IsDigit© on that character to make sure it's a digit.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid
#5
Posted 21 May 2011 - 06:57 PM
write this function :)
public static int[] transformation(int x)
{
string s,numbers = x.ToString();
char[] num = numbers.ToCharArray();
int L=num.Lenght;
int[] x1 = new int[L];
for (int i = 0; i <L; i++)
{
s = num[i].ToString();
x1[i] = Convert.ToInt32(s);
}
return x1;
}
#6
Posted 23 May 2011 - 06:27 AM
Also, if you prefer to use an integer, you can use the mod(%) operator
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









