#### Archived

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

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

This topic is 6074 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 on other sites
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'');
}

##### Share on other sites
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 on other sites
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 on other sites
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!

##### 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; // 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."

##### Share on other sites
Why not change it to something like:
while(i > 0)

##### Share on other sites
yeah, well what if I told you i was an idiot... it worked.

thanks for all the help

##### 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!

1. 1
2. 2
3. 3
4. 4
5. 5
Rutin
17

• 9
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631420
• Total Posts
2999990
×