leetcode Daily Challenge on July 26th, 2020.
Difficulty : Easy
Related Topics : Math
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
- Could you do it without any loop/recursion in O(1) runtime?
- mine
- Java
Runtime: 1 ms, faster than 100.00%, Memory Usage: 36.2 MB, less than 97.48% of Java online submissions
//O(N^2)time N is num.length //O(1)space public int addDigits(int num) { int res = num; while(res > 9){ int t = 0; while(res > 0){ t += res % 10; res /= 10; } res = t; } return res; }
- Java