[LeetCode] 258. Add Digits
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: 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?
class Solution {
public int addDigits(int num) {
// 將num除以10 然後將所有餘數相加
// 如果sum(餘數)除以10 ==0 return 餘數
// num除以10 然後將所有餘數相加
//!!不能用迴圈或遞迴
int remind = 0;
int temp = 0;
while(num != 0){
remind += num % 10;
num /= 10;
if(num==0 && remind>=10)
{
num = remind;
remind = 0; //忘記歸零,搞好久
}
}
return remind;
}
}
留言
張貼留言