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

      

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    java中JSON转换
    使用Admin监控
    linux安装tomcat
    SpringBoot整合Redis
    linux6.8安装docker
    使用Actuator监控
    SpringBoot集成阿里巴巴Druid监控
    使用Log4j日志处理
    SpringBoot多数据源
    SpringBoot文件上传下载
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12410902.html
Copyright © 2011-2022 走看看