Easy
,Math
Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0
Constraints:
num
<= 231 - 1Follow up: Could you do it without any loop/recursion in O(1)
runtime?
function addDigits(num) {
if (num < 10) return num;
return addDigits((num % 10) + addDigits(Math.floor(num / 10)));
}
MarsgoatApr 26, 2023
function addDigits(num) {
return ((num - 1) % 9) + 1;
}
吉神:這題O(1)不是基本嗎?9的倍數檢查方式不是國小教的嗎??
我道歉嗚嗚嗚,我就爛。
MarsgoatApr 26, 2023
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
Yen-Chi ChenWed, Apr 26, 2023
class Solution:
def addDigits(self, num: int) -> int:
return (num - 1) % 9 + 1 if num else 0
Yen-Chi ChenWed, Apr 26, 2023
public int AddDigits(int num) {
if (num == 0) return 0;
int r = num % 9;
return r == 0 ? 9 : r;
}
JimWed, Apr 26, 2023
忘了怎麼排版…
class Solution {
public int addDigits(int num) {
return num != 0 ? (num - 1) % 9 + 1 : 0;
}
}
Ron ChenMon, Jun 12, 2023