66. Plus One

84人阅读 评论(0) 收藏 举报
分类:

1,题目要求
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.

The digits are stored such that the most significant digit is at the head of the list.
给了一个字符串数组来代表数字,数组的每位代表一个数字的每一位,其中索引值越小的数字代表的位数越高。求出该数字加一后的字符串数字表达形式。
除了数字0,没有数字是用0开头。
eg:
[2,3] -> [2,4]
[9,9,9] -> [1,0,0,0]
[0] -> [1]

2,题目思路
一开始对题目的理解有误,以为是直接给出加和结果,结果不对。。
观察题目的意思和结果的构造形式,首先是进位的表达,只有在该为9时,会产生进位。
而当所有位都为9时,最后结果一定是1000的形式。

3,程序源码

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int digitLen = digits.size();
        for(int i = digitLen-1; i>=0; i--)//每进行一次循环,说明产生了一次进位
        {
            if(digits[i] + 1 == 10)
                digits[i] = 0;
            else
            {
                digits[i]++;
                return digits;
            }
        }
        //说明数字是9,9,9的形式,加一即为1,0,0,0
        digits[0] = 1;
        digits.push_back(0);//添加一个0

        return digits;                    
    }
};

查看评论

LeetCode 66 — Plus One(C++ Java Python)

题目:http://oj.leetcode.com/problems/plus-one/ Given a non-negative number represented as an arra...
  • dragon_dream
  • dragon_dream
  • 2014-04-02 08:53:48
  • 3410

LeetCode --- 66. Plus One

题目链接:Plus One Given a non-negative number represented as an array of digits, plus one to the number...
  • makuiyu
  • makuiyu
  • 2015-03-19 21:53:21
  • 7823

Plus One python 题解

Plus One python 题解
  • xiaolewennofollow
  • xiaolewennofollow
  • 2015-04-23 20:15:08
  • 1019

LeetCode OJ 系列之66 Plus One --Python

Problem: Given a non-negative number represented as an array of digits, plus one to the num...
  • ln152315
  • ln152315
  • 2015-12-09 01:32:51
  • 775

LeetCode(66)Plus One

题目Given a non-negative number represented as an array of digits, plus one to the number.The digits a...
  • fly_yr
  • fly_yr
  • 2015-08-18 15:38:10
  • 1112

【leetcode】66. Plus One【java】

Given a non-negative number represented as an array of digits, plus one to the number. The digits a...
  • cslbupt
  • cslbupt
  • 2016-12-17 15:43:36
  • 592

[leetcode] 66. Plus One 解题报告

题目链接:https://leetcode.com/problems/plus-one/ Given a non-negative number represented as an array o...
  • qq508618087
  • qq508618087
  • 2015-12-27 11:13:53
  • 320

[leetcode]Plus One C语言

【题目】 Given a non-negative number represented as an array of digits, plus one to the number. The di...
  • noc_lemontree
  • noc_lemontree
  • 2015-08-27 15:23:14
  • 775

66 Plus One

题目链接:https://leetcode.com/problems/plus-one/题目:Given a non-negative number represented as an array o...
  • ChilseaSai
  • ChilseaSai
  • 2015-08-16 16:21:39
  • 142

66. Plus One 难度:easy

题目: Given a non-negative integer represented as a non-empty array of digits, plus one to the in...
  • luoyingmin
  • luoyingmin
  • 2017-01-07 12:32:09
  • 91
    个人资料
    持之以恒
    等级:
    访问量: 4553
    积分: 1683
    排名: 3万+
    文章存档