"Leetcode" Add Digits

Source: Internet
Author: User

ADD Digits

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 have only one 2 digit, return it.

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

Solution:

Consider an O (1) algorithm, starting with the simplest number:

0-9 certainly all correspond to return 0-9 on the line.

Next

10 return 1

11 Return 2

12 Return 3

13 Return 4

......

18 Return 9

19 return 1

......

The law is ready, because eventually all the numbers will be mapped to 0-9 of these 10 numbers, so only to start to consider whether such mappings exist some of the laws of nature, then by the above can be found that the law is as the size of the number itself increases, the last map to the number is actually incremental, but this increment is actually 9 As a model, and for this problem we only care about the remainder of the modulus and do not care about the number itself has a few "modulo 9".

One thing to be aware of is:

0 is special here, only 0 of the numbers themselves map to 0, no other numbers are mapped to 0 and need to be handled separately.

So, in fact, we're going to map a number except 0 to 1-9 of these nine numbers, and think about that the result should be (num-1)% 9 + 1.

The code is as follows:

1 classSolution:2     #@param {integer} num3     #@return {integer}4     defadddigits (self, num):5         ifnum = =0:6             return07         Else:8             return(num-1)% 9 + 1

"Leetcode" Add Digits

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.