Archived

This topic is now archived and is closed to further replies.

Nibbles

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

Recommended Posts

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."

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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;
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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 ?

Share this post


Link to post
Share on other sites
The following doesn''t work because _while_ requires a bool, not an int. or does this only work in C?

  
int i = 123456; // integer

int s = 0; // sum


while(i)
{
s += (i % 10);
i /= 10;
}


Thanks,
Scott

Email
Website

"If you try and don''t succeed, destroy all evidence that you tried."

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites