• No.66 Plus One


    No.66 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.

    题意:给定一个数组表示的非负数,实现该数加1的功能

    注意:从后向前加,注意边界和进位即可。

    细节!

     1 #include "stdafx.h"
     2 #include <map>
     3 #include <vector>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Solution
     8 {
     9 public:
    10     vector<int> plusOne(vector<int> &digits)
    11     {//给定一个数组表示的非负数,实现该数加1
    12         int carry = 0;//保存进位
    13         int size = digits.size();
    14         vector<int> res;
    15         if(size == 0)
    16         { 
    17             res.push_back(1);
    18             return res;
    19         }
    20         res = digits;
    21         for(int i=size-1; i>=0 ; i--)//从后向前加
    22         {
    23             if(i == size-1)
    24             {
    25                 res[i] = (digits[i]+1)%10;
    26                 carry = (digits[i]+1)/10;
    27             }
    28             if(carry == 0)
    29                 break;
    30             else
    31             {
    32                 res[i] = (digits[i]+carry)%10;
    33                 carry = (digits[i]+carry)/10;
    34             }
    35         }
    36         if(carry!=0)
    37             res.insert(res.begin(),carry);
    38         
    39         return res;
    40     }
    41 };
    42 
    43 int main()
    44 {
    45     Solution sol;
    46     int data[] = {9,9,8,4,2};
    47     vector<int> test(data,data+sizeof(data)/sizeof(int));
    48     vector<int> res;
    49     for(const auto &i : test)
    50         cout << i << " ";
    51     cout << endl;
    52     res = sol.plusOne(test);
    53     for(const auto &i : res)
    54         cout << i << " ";
    55     cout << endl;    
    56 }

     

  • 相关阅读:
    一、【注解】Spring注解@ComponentScan
    一致性Hash算法
    垃圾回收器搭配和调优
    JVM的逃逸分析
    简单理解垃圾回收
    类加载机制和双亲委派模型
    VMWare15下安装CentOS7
    HBase协处理器(1)
    依赖注入的三种方式
    Javascript-设计模式_装饰者模式
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4570230.html
Copyright © 2020-2023  润新知