-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddDigits
More file actions
41 lines (31 loc) · 729 Bytes
/
Copy pathaddDigits
File metadata and controls
41 lines (31 loc) · 729 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/******************************************/
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.
/*******************************************/
class Solution {
public:
int addDigits(int num) {
string s;
s= to_string(num);
if(num<10){
return num;
}
int tm = 0;
while (1) {
for (int i = 0; i < s.size(); i++) {
tm = tm+ (s[i] - '0') + (s[s.size() - 1 - i] - '0') ;
}
tm = tm / 2;
if (tm < 10 && tm != 0) {
break;
}
s = to_string(tm);
tm = 0;
}
return tm;
}
};