zoukankan      html  css  js  c++  java
  • lintcode407 加一

    加一 

    给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。

    该数字按照大小进行排列,最大的数在列表的最前面。

    样例

    给定 [1,2,3] 表示 123, 返回 [1,2,4].

    给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

    第一种方法:

     1 class Solution {
     2 public:
     3     /*
     4      * @param digits: a number represented as an array of digits
     5      * @return: the result
     6      */
     7     vector<int> plusOne(vector<int> &digits) {
     8         // write your code here
     9         vector<int> res;
    10         if (digits.empty()) {
    11             return res;
    12         }
    13         int len = digits.size();
    14         long num = 0;
    15         for (int i = 0; i < len; i++) {
    16             num = num * 10 + digits[i];
    17         }
    18         num = num + 1;
    19         while (num) {
    20             int temp = num % 10;
    21             res.push_back(temp);
    22             num = num / 10;
    23         }
    24         reverse(res.begin(), res.end());
    25         return res;
    26     }
    27 };

    第二种方法:

     1 class Solution  
     2 {  
     3 public:  
     4     /** 
     5     * @param digits a number represented as an array of digits 
     6     * @return the result 
     7     */  
     8     vector<int> plusOne(vector<int>& digits)  
     9     {  
    10         int c = 1;  
    11           
    12         for (int i = digits.size() - 1; i >= 0; i--)  
    13         {  
    14             digits[i] = digits[i] + c;  
    15             c = digits[i]/10;  
    16             digits[i] %= 10;  
    17         }  
    18           
    19         if (c > 0)  
    20         {  
    21             vector<int> temp(digits.size()+1, 0);  
    22             temp[0] = c;  
    23             for (int i = 1; i < temp.size(); i++)  
    24             {  
    25                 temp[i] = digits[i - 1];  
    26             }  
    27             return temp;  
    28         } else  
    29         {  
    30             return digits;  
    31         }  
    32     }  
    33 };  
  • 相关阅读:
    【模板】对拍程序
    【洛谷比赛】Agent1
    【NOIP2017】宝藏
    【NOIP2017】逛公园
    【NOIP2016】换教室
    【NOIP模拟】挖宝藏
    【NOIP模拟】健美猫
    【NOIP2014】飞扬的小鸟
    【NOIP2015】子串
    【CQOI2007】余数求和
  • 原文地址:https://www.cnblogs.com/gousheng/p/7642725.html
Copyright © 2011-2022 走看看