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,结果为100…0

解法一:

inplace但插入操作时会产生数组的移位

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = ;
for(int i = digits.size()-; i >= ; i --)
{
int sum = digits[i]+carry;
carry = sum / ;
digits[i] = sum % ;
if(carry == )
break;
}
if(carry == )
digits.insert(digits.begin(), );
return digits;
}
};

解法二:

inplace且数组不用移位

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
for(int i = digits.size()-; i >= ; i --)
{
if(digits[i] <= )
{
digits[i] += ;
return digits;
}
else
{//
if(i != )
digits[i] = ;
else
{
digits[] = ;
digits.push_back();
return digits;
}
}
}
}
};

最新文章

  1. Windows下构建ASP.NET Core+Code First+Docker
  2. SharpFileDB - a file database for small apps
  3. Pop3_解决PKIX:unable to find valid certification path to requested target 的问题
  4. Ajax发送和接收请求
  5. wddm 部署问题解决
  6. canvas刮刮乐
  7. 12天学好C语言——记录我的C语言学习之路(Day 4)
  8. 第四篇、Tomcat 集群
  9. CSDN第四届在线编程大赛2014初赛:带通配符的数
  10. 使用FileUtils简化你的文件操作
  11. [已解决]IndentationError: unindent does not match any outer indentation level
  12. vue框架-学习记录
  13. 9.3AspectJ
  14. spring+springmvc+hibernate整合实例
  15. 每次运行caffe代码之前需要考虑修改的地方
  16. [最新原创电子书]lazarus开发者入门及中级教程
  17. Jquery 只保留数字和小数点(正则)
  18. Postman-自动化传参
  19. STL——配接器(adapters)
  20. Eclipse安卓插件安装

热门文章

  1. 破解ZendStudio 10.1
  2. High-current supply uses standard three-terminal regulator
  3. MySQL MyISAM和InNodb备份与恢复技巧
  4. .NET:异常处理的两条“黄金定律”,求批!
  5. Andorid之Annotation框架初使用(一)
  6. Spark Streaming性能调优详解(转)
  7. calibre怎么转换文件格式
  8. ZentaoPMS 系统的优先级以及修改
  9. Spring定时器XML配置
  10. [Python爬虫] 之六:Selenium 常用控件用法