zoukankan      html  css  js  c++  java
  • [LeetCode] 66. 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.
    

    把一个vector存储的digits当成int来做加法,只+1

    [LeetCode] 2. Add Two Numbers有点像,然后我写出了一样(丑)的代码

    digits的末尾开始遍历,末尾+1,记下进位carry,如果没进位就直接返回digits,否则就继续看下一位,把进位传递下去

    vector<int> plusOne(vector<int>& digits) {
        ++digits[digits.size()-1];
        int carry = digits[digits.size()-1] / 10;
        digits[digits.size()-1] %= 10;
    
        if (carry == 0)
        {
            return digits;
        }
    
        for(int i = digits.size()-2; i >= 0; i--)
        {
            digits[i] += carry;
            carry = digits[i] / 10;
            digits[i] %= 10;
        }
    
        if (carry != 0)
        {
            digits.insert(digits.begin(), 1);
        }
    
        return digits;
    }
    

    再看看LeetCode上其他代码,很简洁,但不是我现在能想出来的代码

    由于是+1,digits[i]进位完后肯定是0,carry为1,所以循环里直接digits[i]++

    vector<int> plusOne(vector<int> &digits) {
        for(int i = digits.size() - 1; i >= 0; i --){
            digits[i] ++;
            if(digits[i] < 10)
                break;
            digits[i] = 0;
        }
        if(digits[0] == 0){ // 99 + 1 = 100这种
            digits[0] = 1;
            digits.push_back(0);
        }
        return digits;
    }
    
  • 相关阅读:
    Firefox扩展IE Tab Plus内置功能导致浏览所有网页加载superfish.com脚本
    iconv编码转换
    Firefox扩展IE Tab Plus内置功能导致浏览所有网页加载superfish.com脚本
    mysql导入邮件
    Rails gem 打包css javascript 提升网站性能 jammit 简介
    装箱/拆箱测试一例(转)
    nifity scaffold gem
    软硬链接
    软硬链接
    git服务搭建
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9574480.html
Copyright © 2011-2022 走看看