Plus One

本文介绍了一个非负整数数组加一的问题解决方案,包括Python和C语言实现方式。通过对数组从末位开始遍历并判断是否进位,实现了整数加一操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目详情: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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值