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

      

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    ReactNative 打包 APK
    ReactNative常用命令
    ReactNative之坑:停在gradle一直出点
    Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构
    tensorflow 安装升级
    sqlserver 全库查询 带架构
    气象数据资料整理
    poj2841
    cf1430e
    cf1436d
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12410902.html
Copyright © 2011-2022 走看看