LeetCode 258 Add Digits (Number Addition, number root)
Translation
Given a non-negative integer number, repeat all its numbers until the last result is only one digit. For example, given sum = 38, this process is like: 3 + 8 = 11, 1 + 1 = 2, because 2 only has one digit, so it is returned. Then, can you complete it in O (1) time without repeating or recursion?
Original
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?
Analysis
Actually, I don't write it, and neither loop nor recursion can be used ...... What else can I do.
Then I read the prompt from LeetCode and an article on Wikipedia: Digital root.
With this, it will be easy. For details about this formula, refer to the Wikipedia by yourself, because it is too long to translate.
Code
class Solution {public: int floor(int x) { return (x - 1) / 9; } int addDigits(int num) { return num - 9 * floor(num); }};