-3

I want to find the sum of the digits of the number entered in JAVA. I want to encode this algorithm.

Please enter a number= 4562

sum= 4+5+6+2

and I would like to divide the sum of the last number

sum=17/2

but I did not get to separate these numbers. If you know, could you please inform me?

Osmani
  • 669
  • 7
  • 19
  • What did you try? Did you do any code yet? – Osmani Oct 28 '15 at 22:41
  • Did you try a simple search here for `java sum digits of number` before posting? I see about three dozen answered questions at the top of the results that would answer this **exactly**. Here's one I found about four posts down: http://stackoverflow.com/questions/27096670/how-to-sum-digits-of-an-integer-in-java?s=7|1.2325. *Always* search here first before posting a new question; chances are extremely good (especially for beginner questions) that it has been asked and answered here before. – Ken White Oct 28 '15 at 22:42
  • In my program, input number is not definite. User should enter a number. – Gülcan Ertop Oct 28 '15 at 22:55

2 Answers2

-1

What is the range of the number you wish to encode ? You could determine the number of digits in your number to be encoded, say 'n'; in your example 'n' would be 4.

int x = 4562;
int sum = 0;
sum += (x/1000); x %= 1000;
sum += (x/100); x %= 100;
sum += (x/10); x %= 10;
sum += (x/1);
int result = 0;
if (x != 0)
   result = sum / x;

This algorithm can be coded using the aforementioned 'n'... Note that your algorithm doesn't make much sense in case the last digit would be a 0 !

  • Thank you, but input number is not definite in my program. User'll enter a number and I'll do transactions. For example; User gave 1478. and my programme (1+4+7+8) = 20 after divide to last number 20/8 – Gülcan Ertop Oct 28 '15 at 23:02
-2
int number = originalNumber;
int sum = 0;
while (number > 0) {
    sum += number % 10;
    number /= 10;
}
int result = sum / (originalNumber % 10);

Doesn't look like you thought it a lot...

Alberto S.
  • 7,409
  • 6
  • 27
  • 46
  • You should have asked her progress before giving the solution. – Osmani Oct 28 '15 at 22:47
  • Thank you, but input number is not definite in my program. User'll enter a number and I'll do transactions. For example; User gave 1478. and my programme (1+4+7+8) = 20 after divide to last number 20/8 – Gülcan Ertop Oct 28 '15 at 22:58