您的位置:首页 > 其它

leetcode 66. Plus One

2017-07-05 21:36 363 查看
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.

实现一个整数数组加一的操作,只要建立一个flag记录每次运算是否产生进位即可

public class Solution {
public int[] plusOne(int[] digits) {
int flag = 0;
int len = digits.length-1;
int tem = (digits[len]+1+flag)%10;
flag = (digits[len]+1+flag)/10;
digits[len] = tem;
len--;
while(len>=0){
tem = (digits[len]+flag)%10;
flag = (digits[len]+flag)/10;
digits[len] = tem;
len--;
}
if(flag==1){
int[] res = new int [digits.length+1];
res[0] = flag;
for(int i=1;i<res.length;i++){
res[i] = digits[i-1];
}
return res;
}
int res[] = new int[digits.length];
for(int i=0;i<res.length;i++){
res[i] = digits[i];
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: