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;
    }
    

      

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    vim使用笔记
    想象的天空
    修电脑记
    反编译 Component重要类,全文解释 - 组件篇
    被动扫描和主动处理的比较
    第一次运行起来XAML
    学习 Aero 随笔
    Google AdSense 申请已得到批准
    延迟加载的一般实现
    看见几篇文章,收藏一下。
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12410902.html
Copyright © 2011-2022 走看看