"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)"