[Java] Add Digits number Add

Source: Internet
Author: User

Leetcode original title Link: https://leetcode.com/problems/add-digits/

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

For example:

Given num =, the process is Like:3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit and return it.

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

Brief translation:

Given a non-zero integer num, repeat the number on the sum to know that there is only one digit position.

For example, given the number 38, the run result is 3+8 = 11, 1+1 = 2. Because 2 has only one digit, it returns 2.

Requirement: Complete the calculation in O (1) Run time without the help of loops and recursion.

Brief analysis:

The topic asks, does not use the cycle and the recursion premise, solves this problem.

Based on the experience, I wrote the following code:

public static int adddigits (int num) 
	{
		num = sumdigits (num);
		if (Num <) return
			num;
		else return
			adddigits (num);
    }
	private static int sumdigits (int num)
	{
		if (num <) return
			num;
		else return
			sumdigits (NUM/10) +num%10;
	}
This code is AC. But I am careful, not ah ... I use recursion here.

So while AC is, it's actually wrong.

There is another way to solve this problem.
So let's try a couple of numbers and try to find the rules ...

Input: 1,2,3,4,5,6,7,8,9,10 11, 12, 13, 14, 15, 16, 17, 18, 19,20 results: 1, 2,3,4,5,6,7,8,9,1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2

According to the above attempt, we can find that there is a regular.

The result is satisfied, (num-1)%9+1

So you have the following code:

public static int adddigits (int num) 
	{return
	    (num-1)%9+1;
    }

The answer is the correct answer to AC ...

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.