[LeetCode-interview algorithm classic-Java implementation] [066-Plus One (add One)], leetcode -- java
[066-Plus One (Plus One )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Theme
Given a number represented by an array, add one to it.
Each digit is stored in an array. Array subscript from large to small indicates that the number is from low to high.
Solutions
Directly solve the problem and set a carry flag carry. The initial value is 1, indicating that 1 is added. tmp = a [x] + carry starts from the digit bit,
A [x] = tmp % 10, carry = tmp/10. If carry is not 0, perform operations on the next bit, after all the digits are processed or carray is 0, the system exits. If carray is not 0, it means that the entire array needs to be expanded to a number.
Code Implementation
Algorithm Implementation class
Public class Solution {public int [] plusOne (int [] digits) {int carry = 1; // carry mark, the carry mark in the next position is int tmp; for (int I = digits. length-1; I> = 0; I --) {tmp = digits [I]; digits [I] = (tmp + carry) % 10; // calculate the current bit's new value carry = (tmp + carry)/10; // calculate the new carry if (carry = 0) {// you can exit break without carrying;} if (carry = 1) {// There Is A carrying int [] result = new int [digits. length + 1]; System. arraycopy (digits, 0, result, 1, digits. length); result [0] = carry; return result;} else {return digits ;}}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/47203315]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.