converted to string from int, now add each character (number)

Started by
7 comments, last by Nibbles 22 years, 5 months ago
Hi, say i have the integer 12345, how do get the sum of each digit added together? IE: 1+2+3+4+5 = sum. What i''ve done so far is converted the integer (12345) into a string, but now I''m not sure what to do next. I''m doing this in Java, Thanks, Scott Email Website
"If you try and don''t succeed, destroy all evidence that you tried."
Advertisement
you could try

int sum_it(char* str,int nVals)
{
int tot=0;

for(int i=0;i {
tot+=(int)str;
}

tot-=nVals*((int)''0'');
return tot;
}
Try this.. it''s C code but i''m sure you can convert it.

int x=123456;
int i=1;
int sum=0;
int n;
do
{
n=(x%(i*10))/i;
sum+=n;
i*=10;

}while(n);

Now sum equals 21.

This isn''t the code I posted - taggs missing so here is an explanation instead

1= (int)(''1''-''0'')
2= (int)(''2''-''0'')
etc...

nuf said ?
You don''t need to convert to string:
int i = 123456;  // integerint s = 0;       // sumwhile(i){  s += (i % 10);  i /= 10;} 



I wanna work for Microsoft!
The following doesn''t work because _while_ requires a bool, not an int. or does this only work in C?

  int i = 123456;  // integerint s = 0;       // sumwhile(i){    s += (i % 10);    i /= 10;}  


Thanks,
Scott

Email
Website

"If you try and don''t succeed, destroy all evidence that you tried."
Why not change it to something like:
while(i > 0)
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
yeah, well what if I told you i was an idiot... it worked.

thanks for all the help
quote:Original post by wojtos
..._while_ requires a bool, not an int.

Just for further reference, all C/C++ conditional simply require an expression that evaluates to zero or non-zero. This has interesting implications when you iterate and decrement a variable: if the variable somehow successfully drops below zero, the loop will never end (which is why it''s actually a good idea to use i>0).

The same applies to if-conditionals.


I wanna work for Microsoft!

This topic is closed to new replies.

Advertisement