问题描述:
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.
分析:这道题的题意是说,有一个非负的数组代表一个大数,那么这个大数+1之后是多少?
这个比较简单,初始进位为1,当进位为0时,返回原数组,当循环退出时,如果进位仍为1,那么就需要分配一个新的数组来存储,新的数组中第一位为1,其余均为0;
java代码:348ms
public class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
int[] res;
if(length<=0)
return digits;
int carry = 1;
for(int i = length-1;i>=0;i--){
int val = digits[i]+carry;
carry = val/10;
digits[i] = val%10;
if(carry==0)
return digits;
}
if(carry>0){
res = new int[length+1];
res[0] = carry;
return res;
}else
return digits;
}
}
C语言代码如下:0ms
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int carry = 1;
int i;
for(i = digitsSize-1;i>=0;i--){
int val = digits[i]+carry;
carry = val/10;
digits[i] = val%10;
if(carry==0)
break;
}
if(carry){
int *res = (int*)calloc(digitsSize+1,sizeof(int));
res[0] = 1;
*returnSize = digitsSize+1;
return res;
}else
{
*returnSize = digitsSize;
return digits;
}
}