Description:
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?

题意:给定一个非负的整数,将这个数的各个位相加知道最终的结果是一位时停止,并返回这个数;并且不使用循环和递归;

解法:如果这个数是0的话,那么肯定就是0了;我们发现如果这个数是9的倍数的话,那么结果就是9;否则就是对9取余;

class Solution {
public int addDigits(int num) {
if (num == 0) {
return 0;
}
return num % 9 == 0 ? 9 : num % 9;
}
}