题目详情:https://leetcode.com/problems/plus-one/#/description
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.
你可以认为这个非负整数中不以0开始,但是数字0除外。
The digits are stored such that the most significant digit is at the head of the list.
数组中各个数字越靠前权重越大。
Python
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i=len(digits)-1
while(digits[i]+1 > 9 and i >= 0): #从后往前扫描,
digits[i]=0 #直到遇到某位数加1<=9停止
i=i-1
if i==-1 : #若循环结束之后,i==-1,说明digits的各位数字都为9
digits.insert(0,1)#需要在第一位之前插入1即可,后面的各个位的值全为0
else:#若i!=-1说明循环在中间的某位数上就停止了,该位数digits[i]+1<=9
digits[i]=digits[i]+1 #只需要将该位数置为digits[i]=digits[i]+1
return digits
c语言:
/**
* Return an array of size *returnSize.
* 返回一个returnSize大小的数组
* Note: The returned array must be malloced, assume caller calls free().
* 注意:返回的数组必须分配内存,如果没有分配内存,我们会认为调用者调用了free()函数。(感觉怪怪的)
*/
int* plusOne(int* digits, int digitsSize, int* returnSize) {
if ( digits==NULL || digitsSize<1)
return NULL;
int i=digitsSize-1;
int* newDigits=NULL;
while( digits[i]+1 > 9 && i>=0 )
{//从后往前扫描,直到遇到直到遇到某位数digits[i]+1<=9或者i<0时,停止循环
digits[i]=0;
i--;
}
if( i == -1 ) //溢出的情况
{
*returnSize=digitsSize+1;
newDigits=(int*)malloc(sizeof(int)*(*returnSize));
memcpy(newDigits+1,digits,digitsSize*sizeof(int));
newDigits[0]=1;
}
else
{
*returnSize=digitsSize;
newDigits=(int*)malloc(sizeof(int)*(*returnSize));
memcpy(newDigits,digits,sizeof(int)*(*returnSize));
newDigits[i]=digits[i]+1;
}
return newDigits;
}
学好英语的重要性,我又没有看懂题目[衰]。
函数原型:
void *memcpy(void*dest, const void *src, size_t n);
函数功能:
从src指向地址为起始地址的连续n个字节的数据复制到以destin指向地址为起始地址的空间内。
头文件
#include<string.h>
返回值
函数返回一个指向dest的指针。
memset()函数原型:
void *memset(void *s,int c,size_t n)
函数功能:
对以s为起始地址的前n个字节全部置为c
头文件
#include<string.h>