Leetcode Plus One

Source: Internet
Author: User

Given a non-negative number represented as an array of digits, plus one to the number.

The digits is stored such, the most significant digit was at the head of the list.

Problem Solving Ideas:

The original array is processed first. From the end of the array to start checking forward, if the current number is <9, you add 1 without carry, jump from the loop, if the current number equals 9, the description plus 1 involves carrying, and add 1 after the current number should be recorded as 0, continue to loop processing.

When the original array is processed, it is also necessary to determine whether the current No. 0 bit has changed to 0, if it has become 0, the description is similar to 99+1, which requires rounding. Others are not required.

Generally, the problem of the operation of the numbers should consider the boundary, especially the overflow.

Java Code:

 Public int[] PlusOne (int[] digits) {intLen =digits.length;  for(inti=len-1; i>=0; i--){            if(Digits[i] < 9) {Digits[i]++;  Break; }Else{Digits[i]= 0; }        }                int[] newdigits; if(Digits[0] = = 0) {newdigits=New int[Len+1]; newdigits[0] = 1;  for(inti = 1; i< newdigits.length;i++) {Newdigits[i]= Digits[i-1]; }            returnnewdigits; }        returndigits; }

Reference:

1. http://www.cnblogs.com/springfor/p/3888002.html

Leetcode Plus One

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.