(leetcode) Add Digits---integers everybody add

Source: Internet
Author: User

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

For example:

Givennum = 38, the process is like:3 + 8 = 11,1 + 1 = 2. Since2have only one digit, return it.

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


Problem Solving Analysis:

Solution One:

The remainder is added to Num, and the remainder is added until NUM is less than two digits.

#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object):    def adddigits (self, num): While        num >= 10 :            num = (NUM/10) + num%        return num


Solution Two:

The other method is relatively simple and can be illustrated by examples. Assuming that the number entered is a 5 digit num,

Num's members are A, B, C, D, E, respectively. Has the following relationship: num = A * 10000 + b * + + c * + + D * + E

That is: num = (A + B + C + D + E) + (A * 9999 + b * 999 + c * + D * 9)

Because A * 9999 + b * 999 + c * + D * 9 must be divisible by 9, so the num modulo results in addition to 9

The result is the same as a + B + C + D + E modulo except 9. Perform the same operations on the number A + B + C + D + E repeatedly,

The final result is a 1-9 number plus a bunch of numbers, the leftmost number is 1-9, the right number is always

Can be divisible by 9.

Attention:

To handle special cases, when the number is 0, please return directly to 0


#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object):    def adddigits (self, num):        if num > 0:
   
    return 1 + (num-1)% 9        else:            return 0
   



(leetcode) Add Digits---integers everybody add

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.