How can i separate number and add them?
-
If i have any number like : 1234 and i want to do 1+2+3+4 = 10 What should i do? and what method should i use ? -Thanks
Peter
string number="1234"; int total=0; for(int i=0;i { total+=Int32.Parse(number); }
It is said that the most complex structures built by mankind are software systems. This is not generally appreciated because most people cannot see them. Maybe that's a good thing because if we saw them as buildings, we'd deem many of them unsafe.
-
string number="1234"; int total=0; for(int i=0;i { total+=Int32.Parse(number); }
It is said that the most complex structures built by mankind are software systems. This is not generally appreciated because most people cannot see them. Maybe that's a good thing because if we saw them as buildings, we'd deem many of them unsafe.
-
How is it "tricky"?
It is said that the most complex structures built by mankind are software systems. This is not generally appreciated because most people cannot see them. Maybe that's a good thing because if we saw them as buildings, we'd deem many of them unsafe.
-
How is it "tricky"?
It is said that the most complex structures built by mankind are software systems. This is not generally appreciated because most people cannot see them. Maybe that's a good thing because if we saw them as buildings, we'd deem many of them unsafe.
Here is a method that can work, should in theory also be able to add numbers in string with chars.
string s = "1234"; int total = 0; foreach (char c in s) { int x; int.TryParse(c.ToString(), out x); total += x; }
-
Here is a method that can work, should in theory also be able to add numbers in string with chars.
string s = "1234"; int total = 0; foreach (char c in s) { int x; int.TryParse(c.ToString(), out x); total += x; }
..and the shortest one:
string s = "1234"; int total = s.ToCharArray().Sum((x) => int.Parse(x.ToString()));
;) -
..and the shortest one:
string s = "1234"; int total = s.ToCharArray().Sum((x) => int.Parse(x.ToString()));
;)Naaah ;)
int total = s.ToCharArray().Sum((x) => ((int)x)-48);
(ok ok , it is more of a hack ;) )
-
Naaah ;)
int total = s.ToCharArray().Sum((x) => ((int)x)-48);
(ok ok , it is more of a hack ;) )
But you can still leave out the brackets around
x
:P ;) -
If i have any number like : 1234 and i want to do 1+2+3+4 = 10 What should i do? and what method should i use ? -Thanks
Peter
You should use the modulus or remainder function and integer division to solve this problem. Using a divisor of 10 you extract one decimal digit at a time from the number. The same technique with a divisor of 16 can be used to extract hexdecimal digits.
Int32 num = 123456789; Int32 sum = 0; Int32 temp = num; while (temp > 0) { sum += temp % 10; // sum remainders temp = temp / 10; // integer division } Console.WriteLine("Sum of all digits in {0} is {1}", num, sum);
AlanN