zoukankan      html  css  js  c++  java
  • 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 }

     

  • 相关阅读:
    leecode 240. 搜索二维矩阵 II
    leecode 103. 二叉树的锯齿形层序遍历
    leecode 362. 敲击计数器
    leecode 152. 乘积最大子数组
    leecode 560. 和为K的子数组
    面试题 08.12. 八皇后
    leecode 450. 删除二叉搜索树中的节点
    leecode 384. 打乱数组
    leecoode 138. 复制带随机指针的链表
    mysql基本指令2
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4570230.html
Copyright © 2011-2022 走看看