public static int sumDigitsInNumber (int number) {
}
what to write inside this method n more importantly why ???
when you write System......print..(method (546))... you are nt done?? why??
anupam jha
Level 7
help plz
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
anupam jha
5 January 2021, 14:56
i do understand maths part what i wanted actually is to clear the why thing..Thanks for the answer.Great Answer !!!
0
remote87
5 January 2021, 18:10solution
Great! Love I helped! Rate my answer?
+3
remote87
5 January 2021, 08:59
Hi there! You need to calculate or sum all the digits of the given 3 - digits number. what I mean: you have the number 546, so you need to sum 5 + 4 + 6, got it?
If I must not use a loop or something complex, I would do something like this:
The modulo ( % ) operator returns the remainder of the division so I can get the last digit of my number:
546 % 10 = 6 ( 546 / 10 is 540, the / operator returns only the int result of the division ).
So my approach is first I will get the last digit and save it in the ones variable ( int ones ), after that I want to get the middle digit, so number is divided by 10 but with / operator, which like we have said, returns the integer result of the division, or number = number / 10 ( this is equal to number /= 10 and the result is 54. Why? 54 x 10 = 540, we already got the digit 6 ). Now, I do the same with the tens: number ( 54 ) modulo ( % ) 10 and we get 4 as a remainder: 54 % 10 = 4 remainder. Lastly we need the hundreds digit, well it's easy 54 / 10 = ... 5, we have the remainder 4 already in our tens variable. So, now all we need is to sum all the digits: ones + tens + hundreds, you can save it in a result variable and return result, or directly to return the sum of the digits, as I did. With this approach I hope it's clear for you, what you have to do and why you do it. Using this method, no matter the number, you will always get the result wanted, as long as the number is valid 3 digit number ( 100 - 999 ). Best regards! :) +6