Leetcode--add Digits

Source: Internet
Author: User

Description:

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?

Test instructions is very simple, the easiest way to think of is to loop the iteration, if it is <10 return. The following is a recursive approach.

public class Solution {public    int adddigits (int num) {        if (num <) {            return num;        }        1023        int t = 0;        while (num >= 1) {            t + = num%;            num = NUM/10;        }                return Adddigits (t);    }}

  So what can I do to reduce the complexity to O (1) without recursion and iteration, which reminds me of the formula. To find patterns through data.

Top 30 Data tests:

public static void Main (string[] args) {for (int i=0; i<30; i++) {System.out.println (i + "+ adddigits (i))}}

  

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
21 3
22 4
23 5
24 6
25 7
26 8
27 9
28 1
29 2

Find out the rules.

In fact, this is: (num-1)% 9 + 1

public class Solution {public    int adddigits (int num) {       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.