题目描述:
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.
解题思路:
设置进位,如果数组不够的话记得重新开辟空间。
代码如下:
public class Solution { public int[] plusOne(int[] digits) { int carry = 0; if(digits == null || digits.length == 0) return null; else digits[digits.length - 1] += 1; for(int i = digits.length - 1; i >= 0; i--){ int cur = carry + digits[i]; carry = cur / 10; digits[i] = cur % 10; } if(carry != 0){ int[] newDigits = new int[digits.length + 1]; System.arraycopy(digits, 0, newDigits, 1, digits.length); newDigits[0] = carry; return newDigits; } else { return digits; } } }
时间: 2024-12-07 13:44:00