问题描述:
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.
分析:非负整数,存储在数组中。the most significant digit 最高位存储在列表的第一个,例如:98, array[0] 存储9,array[1]存储8。
定义变量carry存储进位,遍历数组,每次修改digits[i] 与 carry
public int[] plusOne(int[] digits) { if(digits == null || digits.length == 0) return null; int len = digits.length; int carry = 0; //进位,只借用一个变量,不需要数组 for(int i = len - 1; i >= 0; i--){ if(i == len - 1){ carry = (digits[i] + 1 ) / 10; //进位 digits[i] = (digits[i] + 1 ) % 10; //本位 } else { int digit = (digits[i] + carry) % 10; //本位 carry = (digits[i] + carry) / 10; //进位 digits[i] = digit; } } if(carry == 0) return digits; else { int[] new_digits = new int[len + 1]; for (int i = 1; i < new_digits.length; i++) { new_digits[i] = digits[i - 1]; } new_digits[0] = carry; return new_digits; } }