LeetCode 258 Add Digits (Number Addition, number root)

Source: Internet
Author: User

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);    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.