• Plus One


    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.

    Analyse: To reduce complexity, if the current addition does not make carry, then stop pushing numbers into a stack.

     1 class Solution {
     2 public:
     3     vector<int> plusOne(vector<int>& digits) {
     4         vector<int> result;
     5         vector<int> help;
     6         int carry = 1;
     7         int temp = 0;
     8         
     9         for(int i = digits.size() - 1; i >= 0; i--){
    10             temp = digits[i] + carry;
    11         
    12             if(temp >= 10){
    13                 carry = 1; 
    14                 temp %= 10;
    15             }
    16             else{
    17                 carry = 0;
    18                 digits[i] = temp;
    19                 for(int j = i + 1; j < digits.size(); j++){
    20                     digits[j] = help.back();
    21                     help.pop_back();
    22                 }
    23                 return digits;
    24             }
    25             help.push_back(temp);
    26         }
    27         if(carry == 1) help.push_back(1);
    28         while(help.size()){
    29             result.push_back(help.back());
    30             help.pop_back();
    31         }
    32         return result;
    33     }
    34 };
  • 相关阅读:
    git 常用命令
    目录
    算法--双栈排序
    算法--栈的翻转练习题
    算法--双栈队列
    算法--可查询最值的栈练习题
    Spark算子--union、intersection、subtract
    Spark算子--take、top、takeOrdered
    Spark算子--countByKey
    Spark算子--SortBy
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4437578.html
Copyright © 2020-2023  润新知