Add number digit

I need to build a method to add each digit of the string given in the parameter, and as long as only 1 digit is left, for example. 1234 = (1+2+3+4) = 10 = (1+0) = 1 .

At first, I thought that a recursive call or while loop should be accurate. But is there a smarter way? Is using modulo possible?

1234 % 9 = 1 It seems that this works ... But no: 9%9 not equal to 9 , but this value is 0 .

Is there a way to build this function without recursive / for / while?

+5
source share
4 answers

I found a simple algorithm somewhere not so long ago. In fact, it works with %9 , however you need to check the case if modulo this number is 0 .

I bet there are more ways to achieve the result, the simplest code will be in Java as follows:

 int sumAllDigits(int n) { return (n%9 == 0 && n!=0) ? 9 : n%9; } 
+6
source

x%9 actually really works. The only problem is when you get 0, you don’t know whether you should get 0 or 9. But you can look back at your original number: the only thing that can return 0 is 0. So:

 public int digitSum(int input) { if ( input == 0 ) { return 0; } int ret = input % 9; if ( ret == 0 ) { return 9; } return ret; } 
+4
source
 int sumAllDigits(int n) { return (n-1)%9 + 1; } 

Works for all n> = 1

+4
source

Make it a string, then print the sum of char on char. If the result is greater than 9, convert to a string and repeat.

 public class FakeTest { @Test public void testCalc() { Assert.assertEquals("1234 -> 1", 1, calc(1234)); } private int calc(int value) { String svalue = String.valueOf(value); int sum = 0; for (char c : svalue.toCharArray()) { sum += (c - '0'); } return sum > 9 ? calc(sum) : sum; } } 
+1
source

Source: https://habr.com/ru/post/1247129/


All Articles