[LeetCode]66.Plus One

简介:

【题目】

Given a number represented as an array of digits, plus one to the number.

【题意】

给你一个用数组表示的数,求加一之后的结果,结果还是用数组表示。

【分析】

从低位到高位,连续遇到9才能加一进位。

【代码1】

/*********************************
*   日期:2014-01-22
*   作者:SJF0115
*   题号: Plus One
*   来源:http://oj.leetcode.com/problems/plus-one/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        int i;
        for(i = digits.size() - 1;i >= 0;--i){
            if(digits[i] != 9){
                ++digits[i];
                return digits;
            }
            else {
                digits[i] = 0;
            }
        }
        //各位全是9
        if(i < 0) {
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};
int main() {
    Solution solution;
    vector<int> result;
    vector<int> array = {9,9,9};
    result = solution.plusOne(array);
    int n = result.size();
    for(int i = 0;i < n;i++){
        printf("%d",result[i]);
    }//for
    printf("\n");
    return 0;
}


【代码2】

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        add(digits,1);
        return digits;
    }
private:
    //模版:数组表示的大数加一个整数(0-9)
    void add(vector<int> &digits,int value){
        int i;
        //进位
        int c = value;
        int n = digits.size();
        for(i = n - 1;i >= 0;i--){
            digits[i] += c;
            c = digits[i] / 10;
            digits[i] %= 10;
        }
        //还有进位
        if(c > 0){
            digits.insert(digits.begin(),c);
        }
    }
};


目录
相关文章
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
101 0
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode 233. Number of Digit One
给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
162 0
LeetCode 233. Number of Digit One
|
存储 Python
LeetCode 66. Plus One
给定表示非负整数的非空数字数组,加上整数的1。 存储数字使得最高有效数字位于列表的开头,并且数组中的每个元素包含单个数字。 您可以假设整数不包含任何前导零,除了数字0本身。
199 0
LeetCode 66. Plus One
|
存储 算法
LeetCode 66. 加一 Plus One
LeetCode 66. 加一 Plus One
|
存储
LeetCode 66 Plus One(加一)(vector)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50564455 翻译 给定一个以一系列数字表示的非负数,将其加一并转换成数字。
915 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
194 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
314 2

热门文章

最新文章

下一篇
日志分析软件