258. Add Digits
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?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int num = 99999999;//输入的数据
int finaldigit = num;
while (finaldigit >= 10)
{
int k = 0;
while (finaldigit>0)
{
k = k + finaldigit % 10;
finaldigit = finaldigit / 10;
}
finaldigit = k;
}
cout << finaldigit << endl;
return 0;
}