Leetcode 258. Add Digits (number theory)

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

The problem is to find the number root of a number.

The number root has a congruence property: A number with its number root pair (b-1) congruence (b is the binary number).

A simple example of this is clear:

123=1*100+2*10+3

=1* (99+1) +2* (9+1) +3

= (99+2*9) + (1+2+3)

The previous item can be divisible by 9, and the next one is the number of each bit. The number that is obtained after the 1+2+3, still can be so split, go down until the number root.

Therefore a number with its number root pairs (b-1) congruence (b is the binary number).

For the subject, we use this property for the number of roots, because the number of roots is a number, and the number of%9 and num%9 results the same, so we are directly num%9, but the number we find here is not number root, the number is [0,9], and%9 to find out is [1,8], So we add a small processing technique: minus 1 First, and then add 1 after the mold.

class Solution {public:    int adddigits (int  num) {          return1+ (num-1)%9;       }};

Leetcode 258. Add Digits (number theory)

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.