i want to add digits of a number that 23424 then 2+3+4+2+4
how can i do it in CPP that C++
thank you guys
How can i add digits of a number in c++, that if i take 34 then how can i code for sum3+4?
Using % to help you.
23424 % 10 = 4
23424 / 10 = 2342
2342 % 10 = 2
2342 / 10 = 234
and so on.
Good luck, I'm also just a starter of C language learner.
Reply:int add_digits(int n)
{
int i;
int total=0;
char buffer[0xFF];
sprintf(buffer,"%d",n);
for(i=0; buffer[i]; i++)
total+=buffer[i]-'0';
return total;
}
Reply:Access the string of digits as an array. Loop through the array and convert each char to a string, the get the numeric value of the string via atoi(str) and add that to your sum.
Oh, forgot you are using c++. Use an iterator instead of an array :)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment