zoukankan      html  css  js  c++  java
  • [LeetCode 题解]: plusOne

    前言

    【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

    1.题目描述

    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.

    2. 题意

    题目大意:

    给定一个由一组数字构成的数组表示的非负整数, 对这个数进行加一操作,并将结果数组返回。

    数组的首元素存储的是该非负整数的最高位。

    3. 思路

    本题比较简单,主要是练习对STL的vector使用。

    4: 解法

     1 class Solution {
     2 public:
     3     vector<int> plusOne(vector<int> &digits) {
     4         
     5         vector<int>::iterator iter = digits.begin();
     6         digits.insert(iter,1,0);  // 首位增加一位,以防进位加法,最高位不足
     7     
     8         vector<int>::reverse_iterator riter = digits.rbegin();
     9     
    10         int c =1;
    11         // 逆序进位加操作
    12         for(;riter!=digits.rend();riter++)
    13         {
    14              *riter = *riter+c;
    15              if(*riter>=10)
    16              {
    17                 *riter%=10;
    18                 c =1;
    19              }
    20              else
    21              {
    22                 c=0;
    23              }
    24         }
    25         //判断最高位是否为零
    26         iter = digits.begin();
    27         if(*iter==0) digits.erase(digits.begin());
    28     
    29         return digits;
    30     }
    31 };        

    作者:Double_Win

    出处: http://www.cnblogs.com/double-win/p/3706413.html

    声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~

  • 相关阅读:
    文件系统操作与磁盘管理
    文件打包与解压缩
    环境变量与文件查找
    Linux目录结构及文件基本操作
    vim3
    vim2
    vim1
    用户管理
    初识
    第一章
  • 原文地址:https://www.cnblogs.com/double-win/p/3706413.html
Copyright © 2011-2022 走看看