[Leetcode] ADD Digits

Source: Internet
Author: User

Title Description: (link)

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?

Problem Solving Ideas:

1 classSolution {2  Public:3     intAdddigits (intnum) {4         stringCache =to_string (num);5         intresult =0;6          while(true) {7              for(Auto IX = Cache.begin (); IX! = Cache.end (); + +ix) {8Result + = (*ix-'0');9             } Ten              One             if(Result <=9) { A                  Break; -             } -Cache =to_string (result); theresult =0; -         } -         returnresult; -     } +};

Reprint Address: http://my.oschina.net/Tsybius2014/blog/497645

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)

Since A * 9999 + b * 999 + c * + D * 9 must be divisible by 9, the result of Num modulo 9 is the same as the result of a + B + C + D + E modulo except 9.

For the number A + B + C + D + E repeated execution of the same operation, the final result is a 1-9 number plus a string of numbers, the leftmost number is 1-9, the right side of the number will always be divisible by 9.

The final goal of this problem is to constantly add, add to the last, when the result is less than 10 o'clock return. Because the final result is between 1-9 and 9 will not be added to you, so there will not be a result of 0. Because (x + y)% Z = (x% z + y% z)% Z, and because X is z% z = x% Z, the result is (num-1)% 9 + 1, modulo only 91 times, and returns the result after modulo is added.

1 class Solution {2public:3     int adddigits (int  num) {4         return19 1 ; 5     }6 };

[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.