Archived

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

braking him

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

Recommended Posts

I have the following problem: I have an integer number consisting of 1 to 5 numbers, for instance 1(one number:1),1234(four numbers-1,2,3,4)and so on... Part of problem i summing up all the nubers of the nuber(for instance 1234 is 1,2,3,4 so sum is 10).As i said, i dont know the length of nubmber in advance.I am wondering if there is a way to find how many numbers are contained within number, how to brake it and the sum all of them.I tried doing division and modulus operations so for instance 22/10=2(integer, so no remainder) and 22%10=2(this is the remainder) so the sum is 2+2=4, in this case i know that there are two numbers, so it is not applicable.If anyone knows some algorithm(s) and c++ code i would be grateful!

Share on other sites
you pretty much gave the algorithm yourself

int f(int i){	int sum;	for( sum = 0; i; i /= 10)		sum += i % 10;	return sum;}

• Forum Statistics

• Total Topics
628740
• Total Posts
2984470

• 12
• 25
• 11
• 10
• 16