from : https://leetcode.com/problems/add-digits/
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?
思路:
任意x,x为n位数,则
那么,
又因为x%9 < 9, 所以,x%9即为所求。
public class Solution {
public int addDigits(int num) {
return (num-1)%9+1;
}
}
本文提供了一种高效方法,通过数学运算直接得出任意非负整数连续加和直至单数字的结果,无需循环或递归,实现O(1)运行时间。
1309

被折叠的 条评论
为什么被折叠?



