LeetCode #258. Add Digits,

Source: Internet
Author: User

LeetCode #258. Add Digits,

Add Digits

Description:

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:Cocould you do it without any loop/recursion in O (1) runtime?

Hint:A naive implementation of the above process is trivial. cocould you come up with other methods?

Question:

Given a non-negative integer num, add each digit repeatedly until the result has only one digit.
For example:
Given num = 38, the process is like this: 3 + 8 = 11, 1 + 1 = 2. Because 2 has only one digit, return it.
Further consideration:
Can you finish the question during the O (1) running time without repeating?
Tip:
An intuitive solution is to simulate the above process. Can you think of other methods?
How many possibilities are the results?
Are they periodic or random?

Solution:

Observation method
As prompted, the result is only one digit, so the possible number is 0-9.
Use method I code to output the running result of 0-19 cyclically:
''In out in out
0 0 10 1
1 1 11 2
2 2 12 3
3 3 13 4
4 4 14 5
5 5 15 6
6 6 16 7
7 7 17 8
8 8 18 9
9 9 19 1''
The relationship between output and input is as follows:
''Out = (in-1) % 9 + 1''

C ++ code:

1 class Solution {2 public:3     int addDigits(int num) {4         return (num-1)%9+1;5     }6 }

 

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.