Leetcode-258 addDigits
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.
int addDigits(int num)
{
if(num < 10)
return num;
int count = 1;
int num_copy = num;
while(num_copy / 10)
{
count++;
num_copy = num_copy / 10;
}
int a[count];
for( int i = 0;i < count;i++)
{
a[i] = num%10;
num = num /10;
}
int temp_res = 0;
for( int i = 0;i < count;i++)
{
temp_res = temp_res + a[i];
}
if(temp_res < 10)
{
return temp_res;
}
else
{
int result = temp_res / 10 +temp_res % 10;
if(result <10)
return result;
else
return (result / 10 + result%10);
}
}
在网上还看到了一个很巧妙地解法,思路如下:
根据提示,由于结果只有一位数,因此其可能的数字为0 - 9
使用方法I的代码循环输出0 - 19的运行结果:
可以发现输出与输入的关系为:
因此直接一行代码完事
public class Solution {
public int addDigits(int num) {
return 1 + (num-1) % 9;
}
}