LeetCode 66. Plus One

原创 2018年04月15日 12:42:35

两种就解法。

1.简单(投机取巧,充分利用题目中仅仅加1)

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        //题目中有说非空数组因此不用另外判断
        int len=digits.size();
        for(int i=len-1;i>=0;i--)
        {
            if(digits[i]==9) digits[i]=0;//只有全是9才能进位最高位,即多一位
            else 
            {
                digits[i]++;
                return digits;
            }   
        }
        digits[0]=1;
        digits.push_back(0);//全是9才会走到这一步才进行处理把高位变1,多加一位0,题目中说到了最高为放在数组的前面
        return digits;
            
    }
};

2.第二种,通用解法,可以吧C换成更大的数。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        //题目中有说非空数组因此不用另外判断
        int len=digits.size();
        int sum;
        int c=1;//储存了从后一位进位来的数
        for(int i=len-1;i>=0;i--)
        {
         sum=digits[i]+c;
         digits[i]=sum%10;
         c=sum/10;      
        }
        if(c==1) //再大得数最高位进位也得是1
        digits.insert(digits.begin(),1);
        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
  • 7826

【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 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版

leetcode解题之66 # Plus One Java版
  • mine_song
  • mine_song
  • 2017-03-13 09:30:20
  • 215

[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
  • 777

Plus One python 题解

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

[leetcode-66]plus one(java)

问题描述: Given a non-negative number represented as an array of digits, plus one to the number.The dig...
  • zdavb
  • zdavb
  • 2015-07-30 22:48:47
  • 736

(Java)LeetCode-66. Plus One

Given a non-negative number represented as an array of digits, plus one to the number. The digits...
  • u012848330
  • u012848330
  • 2016-11-02 15:03:05
  • 271
收藏助手
不良信息举报
您举报文章:LeetCode 66. Plus One
举报原因:
原因补充:

(最多只允许输入30个字)