【LeetCode】3.Array and String — Plus One 末尾加一,满十则进。

博客围绕非空数组表示的非负整数加一操作展开。介绍了两种方法,一是对数组最后一位加一,考虑特殊情况并使用动态数组;二是将数组提取为数字加一后再放回数组,但受数组长度限制。方法一通过LeetCode检测。

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

 

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

1.按照要求,对数组进行操作。取数组最后一位,进行加一操作。对长度为1的数组单独处理。考虑极端情况:{9,9,9,9}等。需要在数组头部添加1,这里使用动态数组。该方法通过LeetCode检测验收。

class Solution {
public:
       vector<int> plusOne(vector<int>& digits) {
        int length = digits.size();
        if (length == 1) {
            digits[0] = digits[0] + 1;
            if(digits[0]>9)
            {
                digits[0]=digits[0]-10;
                digits.insert(digits.begin(),1);
            }
            return digits;
        }
        digits[length - 1] = digits[length - 1] + 1;
        for (int i = length - 1; i >= 0; i--)
        {
            if (i > 0 && digits[i] > 9) {
                digits[i] = digits[i] - 10;
                digits[i - 1] = digits[i - 1] + 1;
            }
            if (i == 0 && digits[i] > 9) {
                digits[i] = digits[i] - 10;
                digits.insert(digits.begin(), 1);
            }
        }
        
        return digits;
 }
};

2.把所给数组提取为数组,如[1,2,3]提取为123放在一个变量中。对提取的数字加一操作再按位放回原数组中。该方法受限于数组的长度:如定义int型变量存取,则数组所表示的数字最大为232-1.同理,定义为long long型则为264-1. 所以就当练个手,熟悉一下对数组的操作。

       vector<int> plusOne(vector<int>& digits) {
        int length = digits.size();
        if (length == 1)
        {
            int num = digits[length - 1] + 1;
            if (num>9)
            {
                digits.clear();
                digits.push_back(1);
                digits.push_back(num - 10);
            }
            else digits[length - 1] += 1;
        }
        else {
            long long sum = 0;
            auto counter = 0;
            while (digits[counter] == 0) counter++;
            for (auto i = counter; i<length; i++)
            {
                sum += digits[i] * pow(10, length - i-1);
            }
            sum = sum + 1;
            digits.clear();
            while (sum != 0)
            {
                auto t = sum - (sum / 10) * 10;
                digits.insert(digits.begin(),t);
                sum = sum / 10;
            }
        }

        return digits;
 }
//组数法  受限于计算机的最大位数

 

转载于:https://www.cnblogs.com/hu-19941213/p/10930149.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值