zoukankan      html  css  js  c++  java
  • Plus One

    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:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    vector<int> plusOne(vector<int> &digits){
        int carry = 1;
        vector<int> v;
        while(digits.size() > 0){
            int x = digits.back();
            digits.pop_back();
            x = x + carry;
            v.insert(v.begin(),x%10);
            carry = x / 10;
        }
    
        if(carry > 0)
            v.insert(v.begin(),carry);
        return v;
    }
    
    void printVector(vector<int>& v){
        cout << "{";
        for(int i = 0; i < v.size(); i++){
            cout << v[i] << "" ;
        }
    
        cout << "}";
    }
    
    int main()
    {
        int a[] = {9,9,9};
        vector<int> d(&a[0],&a[0] + sizeof(a)/sizeof(int));
        vector<int> v = plusOne(d);
        printVector(v);
        return 0;
    }
    

      

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    grep: Linux基础命令及用法 -- grep
    [功能集锦] 003
    [功能集锦] 002
    [mysql相关集锦] 001
    [eclipse中使用Git插件] 008
    [eclipse相关] 001
    [代码优化集锦]
    [功能集锦] 001
    [java基础] 002
    [java基础] 001
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12410902.html
Copyright © 2011-2022 走看看