407 加一

原题网址:https://www.lintcode.com/problem/plus-one/description

描述

给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。

该数字按照数位高低进行排列,最高位的数在列表的最前面。

您在真实的面试中是否遇到过这个题?  

样例

给定 [1,2,3] 表示 123, 返回 [1,2,4].

给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

标签
数组
 
思路1:直接的做法是将数组转化为整数,注意该整数的类型应定义成 long long 防止数据过大造成运算错误。然后该整数+1,再将其转化为数组,从低位开始依次push到结果数组中,最后将结果数组翻转return出去。
 
AC代码:
class Solution {
public:
    /**
     * @param digits: a number represented as an array of digits
     * @return: the result
     */
    vector<int> plusOne(vector<int> &digits) {
        // write your code here
    vector<int> result;
    int n=digits.size();
    if (n==0)
    {
        result.push_back(1);
        return result;
    }
    long long tmp=0;//注意不能定义成int型,int能表示最大值是2147483647;
    for (int i=0;i<n;i++)
    {
        tmp+=digits[i]*pow(10.0,n-1-i);
    }
    tmp=tmp+1;
    while(tmp)
    {
        int x=tmp%10;
        result.push_back(x);
        tmp=tmp/10;
    }
    reverse(result.begin(),result.end());
    return result;
    }
};

 

思路2:

数组最后一位数直接加1。然后循环判断当前位置(初始值为最后一位)是否超过9,超过就对10取余,前一位加1,当前位前移,继续判断;

循环结束后判断下数组第一位是否超过9,超过就对10取余,新建一个数组,首先将1 push进去,再将原数组中其他数字拷贝进去。

 

AC代码:

class Solution {
public:
    /**
     * @param digits: a number represented as an array of digits
     * @return: the result
     */
    vector<int> plusOne(vector<int> &digits) {
        // write your code here
    int n = digits.size();
    if (n==0)
    {
        digits.push_back(1);
        return digits;
    }
    digits[n-1] = digits[n-1]+1;
    int i = n-1;
    while(digits[i]>=10&&i>0)
    {
        digits[i] = digits[i]%10;
        digits[i-1] = digits[i-1]+1;
        i--;
    }
    
    if (digits[0]>=10)
    {
        digits[0]=digits[0]%10;
        vector<int> result;
        result.push_back(1);
        for (int j=0;j<n;j++)
        {
            result.push_back(digits[j]);
        }
        return result;
    }
    return digits;
    }
};

 

 其他方法:https://blog.csdn.net/ljlstart/article/details/48373713

http://www.cnblogs.com/grandyang/p/5794220.html

 

原文地址:https://www.cnblogs.com/Tang-tangt/p/9215889.html