ADD Digits
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
have only one digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Hint:
- A naive implementation of the above process is trivial. Could come up with other methods?
- What is all the possible results?
- How does they occur, periodically or randomly?
- You could find this Wikipedia article useful.
Assigns a number to the number of people to add and, until the number is only one digit, the output.
Brute force solution.
Class Solution {public: int adddigits (int num) { if (num <) return num; int tem; while (num > 9) { tem = num; num = 0; while (TEM) { num + = tem%; TEM/=;} } return num; }};
Find the Rules
For example, the final answer for 2,11,20,29 is 2, and they are 9 modulo 2.
Class Solution {public: int adddigits (int num) { if (num <= 9) return num; if (num% 9 = = 0) return 9; return num% 9; }};
A simpler way of writing.
Class Solution {public: int adddigits (int num) { return (num-1)%9 + 1; }};
Given a non-negative integer num
, repeatedly add all its digits until the result have only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
have only one digit, return it.
Follow up:
Could do it without any loop/recursion in O (1) runtime?
Hint:
- A naive implementation of the above process is trivial. Could come up with other methods?
- What is all the possible results?
- How does they occur, periodically or randomly?
- You could find this Wikipedia article useful.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode-258-add Digits