您的位置:首页 > 其它

LeetCode(29)-Plus One

2016-04-06 23:09 274 查看

题目:

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