Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, 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?
这是一个数学问题(废话),写下几个例子你会发现每个结果都是num mod 9后的余数。
我的代码:
1 public class Solution { 2 public int addDigits(int num) { 3 if(num%9==0&&num>9){ 4 return 9; 5 } 6 if(num>=10){ 7 num=num%9; 8 } 9 return num; 10 } 11 }
这是我一开始的代码,其实我只是想解决下边界问题。之后看了网上的代码,顿时感觉我的代码有点傻。
修改后:
public class Solution { 2 public int addDigits(int num) { 3 return 1+(num-1)%9; 10 } 11 }