题目:
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.
思路:
- 题意是用一个数组来表示一个非负的整数。范围是0~9的数字,模拟一个加法的加一操作
- 推断是否进位。假设是9,加1就是10,置为0,然后进位。
- 假设超除了界限,又一次设置一个数组,第一位是1。后面是0
-
代码:
public class Solution {
public int[] plusOne(int[] digits) {
int carries = 1;
for(int i = digits.length-1; i>=0 && carries > 0; i--){ // fast break when carries equals zero
int sum = digits[i] + 1;
digits[i] = sum % 10;
carries = sum / 10;
}
if(carries == 0)
return digits;
int[] rst = new int[digits.length+1];
rst[0] = 1;
for(int i=1; i< rst.length; i++){
rst[i] = 0;
}
return rst;
}
}
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。