Friday, May 26, 2017

Add Digits

Problem statement

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Could you do it without any loop/recursion in O(1) runtime?

Example

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. 
Since 2 has only one digit, return it.

Link to GithubCode

Solution

We need use the formula
  • dr(n) = 1 + (n - 1) % 9
public class AddTwoDigits {
//Solution using formula
public static int get(int num) {
return 1+(num-1)%9;
}

No comments:

Post a Comment