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

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            int carry = 1;
            int len = digits.size();
            
            vector<int> res;
            
            for (int i=len-1; i>=0; i--) {
                int cur = carry + digits[i];
                carry = cur / 10;
                cur = cur % 10;
                res.push_back(cur);
            }
            if (carry) {
                res.push_back(1);
            }
            reverse(res.begin(), res.end());
            return res;
        }
    };

    水一发

    第二轮:

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

    The digits are stored such that the most significant digit is at the head of the list.

    参考了一下题解,对于这个问题不用把数字全部遍历判断完,不需进位时可以直接返回。对多一位数字或者无数字输入的情况处理都统一了。

     1 public class Solution {
     2     public int[] plusOne(int[] digits) {
     3         int len = digits.length;
     4         for (int i=len-1; i>=0; i--) {
     5             int d = digits[i];
     6             if (d<9) {
     7                 digits[i]++;
     8                 return digits;
     9             } else {
    10                 digits[i] = 0;
    11             }
    12         }
    13         int[] res = new int[len+1];
    14         res[0] = 1;
    15         return res;
    16     }
    17 }
  • 相关阅读:
    poj 1035 字符串匹配
    拓扑排序的小总结
    POJ1018
    POJ1328详细题解
    POJ1159题解报告
    POJ1088 (滑雪)
    树状树组区间修改,单点修改模板
    spfa模板
    树状树组离散化求逆序对模板
    POJ3723(最小生成树,负权)
  • 原文地址:https://www.cnblogs.com/lailailai/p/3825263.html
Copyright © 2011-2022 走看看