您的位置:首页 > 其它

LeetCode 66 Plus One

2018-01-15 14:15 471 查看
原题:

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

题意:

一个整数按位存储于一个int数组中,排列顺序为:最高位在digits[0] ,最低位在digits[n-1],  

例如,98,存储为:digits[0]=9; digits[1]=8;  

代码及思路:

class Solution {
public int[] plusOne(int[] digits) {
//解题思路:从数组的最后一位开始加1,需要考虑进位,如果到digits[0]位之后仍然有进位存在,则将进位加上
int n = digits.length;
for(int i=n-1;i>=0;i--){
if(digits[i]<9){
digits[i]++;
return digits;
}
//如果不是<9,那就是等于9,把当前位置设置为0后,for循环会继续判断前面一位,如果<9,digits[i]++会自动进位
digits[i] = 0;
}
//如果最后一位也等于9,如(99)那么就没有return,进入这一步
int [] newA = new int [n+1];
newA[0] = 1;
return newA;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: