#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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?
分析:这里的一位是指在十进制下面,只剩一位数
最简单的情况是:先分解然后相加每一位,
如果不使用循环或者递归,在O(1)时间完成。肯定只需要计算一遍
38,
3: 0011
8: 1000
异或操作:变为11
1011
如果是33: 3 + 3 = 6,6+0=6这样不是永远
0011
0011
0000
输入:
33
38
1
100
输出:
6
2
1
1
*/
class Solution {
public:
//将一个数的各个位进行拆分,返回拆分后的累加和。
//拆分使用先 % 10 后 / 10的方法
int getResult(int num)
{
vector<int> result;
int temp;
do
{
temp = num % 10;
result.push_back(temp);
num /= 10;
}while(num);
//遍历求得累加和
int sum = 0;
if(result.empty())
{
return 0;
}
int size = result.size();
for(int i = 0 ; i < size ; i++)
{
sum += result.at(i);
}
return sum;
}
int addDigits(int num) {
int result = num;
while(result >= 10)
{
result = getResult(result);
}
return result;
}
};
void process()
{
int num;
Solution solution;
while(cin >> num )
{
int answer = solution.addDigits(num);
cout << answer << endl;
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:258. Add Digits

最新推荐文章于 2024-06-17 19:54:44 发布
