zoukankan      html  css  js  c++  java
  • [LeetCode]Plus One

    因为忙着做实验写paper,刷题的进度放慢了一点。爬上来更新一下最近做的几道题目。

    Given a number represented as an array of digits, plus one to the number.

    模拟问题。给定输入是一个vector数组,输出加1后的计算结果。

    将进位carry初始值置为1,从数组的最后一位开始加,注意最高位的进位。

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<int> ret;
            int n = digits.size();
            
            int carry = 1;
            const int BASE = 10;
            for(int i=n-1; i>=0; --i)
            {
                int tmp = digits[i]+carry;
                ret.insert(ret.begin(), tmp%BASE);
                carry = tmp>=BASE?1:0; //
            }
            // final carry bit
            if(carry)
                ret.insert(ret.begin(), carry);
            return ret;
        }
    };
    View Code
  • 相关阅读:
    uva 532
    uva 10557
    uva 705
    uva 784
    uva 657
    uva 572
    uva 10562
    usa物价统计
    2019/6/30,道歉书
    名词收集
  • 原文地址:https://www.cnblogs.com/practice/p/3423882.html
Copyright © 2011-2022 走看看