Source: Internet
Author: User

Given a non-negative integer `num` , repeatedly add all its digits until the result have only one digit.

For example:

Given`num = 38`, the process is like:`3 + 8 = 11`,`1 + 1 = 2`. Since`2`have only one digit, return it.

Could do it without any loop/recursion in O (1) runtime?

Hint:

1. A naive implementation of the above process is trivial. Could come up with other methods?
2. What is all the possible results?
3. How does they occur, periodically or randomly?
4. 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:

Given`num = 38`, the process is like:`3 + 8 = 11`,`1 + 1 = 2`. Since`2`have only one digit, return it.

Could do it without any loop/recursion in O (1) runtime?

Hint:

1. A naive implementation of the above process is trivial. Could come up with other methods?
2. What is all the possible results?
3. How does they occur, periodically or randomly?
4. You could find this Wikipedia article useful.

Related Keywords:

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.