"066-plus one (plus a)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory 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 of the digits is stored in one place in the array. Array subscripts from large to small indicate digits from low to high.
Thinking of solving problems
The direct solution, set a carry flag carry, the initial value is 1, indicating plus 1, starting from the lowest bit TMP = A[x] + carry,
A[x] = Tmp%10,carry = TMP/10, if carry does not operate on the next one for 0, until all the digits have been processed or CArray is 0, if the last CArray is not 0, the entire array is extended by 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) {//Finally there is a carry int[] result =New int[Digits.length +1]; System.arraycopy (digits,0, result,1, digits.length); result[0] = carry;;returnResult }Else{returnDigits } }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47203315"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "066-plus One (plus)"