• 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 };
  • 相关阅读:
    chapter 12_1 数据文件
    chapter11_3 字符串缓冲
    chapter11_2 Lua链表与队列
    chapter11_1 Lua数组、列表
    chapter9_4 非抢占式的多线程
    Java设计模式
    java内存回收机制
    javaIO流概述
    java集合概述
    java多线程
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4437578.html
Copyright © 2020-2023  润新知