Java [Leetcode 258]add Digits

Source: Internet
Author: User

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

Problem Solving Ideas:

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, so the result is (num-1)% 9 + 1, modulo only 91 times, and add a return after modulo the result

The code is as follows:

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

  

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