Given a non-negative integer
num
, repeatedly add all its digits until the result has only one digit.
For example:
Given
num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Could you do it without any loop/recursion in O(1) runtime?
Solution1: with while loop
public class Solution { public int addDigits(int num) { if (num < 10) { return num; } int res = 0; while (num / 10 >= 1) { res = 0; res += num % 10; num = num / 10; res += num; num = res; } return res; } }
public class Solution { public int addDigits(int num) { if (num == 0) { return 0; } if (num % 9 != 0) { return num % 9; } else { return 9; } } }Or:
public class Solution { public int addDigits(int num) { return (num - 1) % 9 + 1; } }
No comments:
Post a Comment