"Leetcode-Interview algorithm classic-java implementation" "066-plus One (plus)"

Source: Internet
Author: User

"066-plus one (plus a)" "leetcode-Interview algorithm classic-java Implementation" "All Topics folder Index" Original Question

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.

Main Topic

Given a number represented by an array. Add an action to it.
Each digit is stored in one place in the array. Array subscripts from large to small indicate digits from low to high.

Thinking of solving problems

Direct solution, set a carry flag carry, the initial value is 1. Represents plus 1, starting with the lowest bit TMP = A[x] + carry.
A[X] = tmp%10. carry = TMP/10, assuming that carry does not operate on the next one for 0, until all the digits have been processed or the CArray is 0, let's say that the last CArray is not 0 to show that the entire array is going to extend one digit.

Code Implementation

Algorithm implementation class

 Public classSolution { Public int[]PlusOne(int[] digits) {intcarry =1;//Carry flag, next one comes with carry flag        inttmp for(inti = digits.length-1; I >=0;            i--) {tmp = digits[i]; Digits[i] = (tmp + carry)%Ten;//Calculate the new value of the current bitCarry = (TMP + carry)/Ten;//Calculate a new rounding            if(Carry = =0) {///You can quit without rounding up.                 Break; }        }if(Carry = =1) {//Last other rounding            int[] result =New int[Digits.length +1]; System.arraycopy (digits,0, result,1, digits.length); result[0] = carry;;returnResult }Else{returnDigits }    }}
Assessment Results

  Click on the picture, the mouse does not release, drag a position, release after the new form to view the full picture.

Special Instructions Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47203315"

leetcode-Interview Algorithm classic-java implementation "066-plus one (plus)"

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.