Leetcode—66.加一【简单】
2023每日刷题(十一)
Leetcode—66.加一
实现代码1
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
int num = 0;
int i = 0;
int arr[110] = {0};
// 进位标识符
int carryOver = 0;
int cnt = digitsSize - 1;
int tmp = digits[cnt] + 1;
if(tmp == 10) {
carryOver = 1;
arr[cnt] = 0;
} else {
arr[cnt] = tmp;
}
int cur = cnt;
while(cnt--) {
if(carryOver == 0) {
arr[--cur] = digits[cnt];
} else {
tmp = digits[cnt] + 1;
if(tmp == 10) {
carryOver = 1;
arr[--cur] = 0;
} else {
carryOver = 0;
arr[--cur] = tmp;
}
}
}
if(carryOver) {
*returnSize = digitsSize + 1;
} else {
*returnSize = digitsSize;
}
cur = *returnSize;
int *arrList = (int *)malloc((cur) * sizeof(int));
while(digitsSize--) {
arrList[--cur] = arr[digitsSize];
}
if(carryOver) {
arrList[0] = 1;
}
return arrList;
}
运行结果
实现代码2
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
int cnt = 0;
int i;
for(i = 0; i < digitsSize; i++) {
if(digits[i] == 9) {
cnt++;
}
}
// 全部元素都为9
if(cnt == digitsSize) {
int *ans = (int *)malloc((digitsSize + 1) * sizeof(int));
ans[0] = 1;
int j;
for(j = 1; j < digitsSize + 1; j++) {
ans[j] = 0;
}
*returnSize = digitsSize + 1;
return ans;
} else {
int *ans = (int *)malloc(digitsSize * sizeof(int));
int c = 0;
int i;
for(i = digitsSize - 1; i >= 0; i--) {
if(i == digitsSize - 1) {
ans[i] = digits[i] + 1;
c = ans[i] / 10;
ans[i] = ans[i] % 10;
} else {
ans[i] = digits[i] + c;
c = ans[i] / 10;
ans[i] = ans[i] % 10;
}
}
*returnSize = digitsSize;
return ans;
}
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!