Leetcode 258. ADD Digits

Source: Internet
Author: User

Problem:

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?

The original idea is to add and judge the repeated loops until a satisfied solution is found. By referring to other people's answers, we find that the problem is to ask for "number root".

This method is judged by the cyclic addition until a viable solution is found:

classSolution { Public:    intAdddigits (intnum) {        intAdd =0;  while(Num >=Ten)        {             while(Num >0) {Add+ = num%Ten; Num/=Ten; } num=add; }        returnnum; }};

However, due to the complexity of time exceeds the requirements of the topic, it is considered to the "number root" solution.

The enumeration indicates that:
10 1+0 = 1
11 = 2
12 1+2 = 3
13 1+3 = 4
14 1+4 = 5
15 1+5 = 6
16 1+6 = 7
17 1+7 = 8
18 1+8 = 9
19 1+9 = 1
20 2+0 = 2

So we can draw a regular, every 9 cycles. To handle a multiple of 9, we write as (n-1)% 9 + 1. This can be done by:

class Solution {public:    int adddigits (int  num)     {         return 1 9 1 ;    }};

Leetcode 258. 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.