Re: [閒聊] 每日LeetCode已回收
258. Add Digits
給你一個數字num,把他的每個位數的數字不斷相加直到最後只剩一位數並返回。
Example:
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.
Input: num = 0
Output: 0
思路:
1.用遞迴不斷的把當前數字全部加起來,遞迴結束條件是num<=9。
Java Code:
-------------------------------------------------
class Solution {
public int addDigits(int num) {
if (num <= 9) {
return num;
}
int res = 0;
while (num > 0) {
res += num % 10;
num /= 10;
}
return addDigits(res);
}
}
-------------------------------------------------
--
https://i.imgur.com/CBMFmWk.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1682525315.A.7D3.html
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 301 之 719 篇):