?LeetCode刷題實戰(zhàn)258:各位相加
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
示例
輸入: 38
輸出: 2
解釋: 各位相加的過程為:3 + 8 = 11, 1 + 1 = 2。由于 2 是一位數(shù),所以返回 2。
進(jìn)階:
你可以不使用循環(huán)或者遞歸,且在 O(1) 時間復(fù)雜度內(nèi)解決這個問題嗎?
解題
class Solution {
public int addDigits(int num) {
if (num == 0)
return 0;
if (num % 9 == 0)
return 9;
return num % 9;
}
}
評論
圖片
表情
