当前位置:网站首页>LeetCode_66_加一
LeetCode_66_加一
2022-08-08 10:37:00 【Fitz1318】
题目链接
题目描述
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0
之外,这个整数不会以零开头。
示例 1:
输入:digits = [1,2,3]
输出:[1,2,4]
解释:输入数组表示数字 123。
示例 2:
输入:digits = [4,3,2,1]
输出:[4,3,2,2]
解释:输入数组表示数字 4321。
示例 3:
输入:digits = [0]
输出:[1]
提示:
1 <= digits.length <= 100
0 <= digits[i] <= 9
解题思路
分为以下三种情况
- 末位无进位,则末位加一即可。因为末位无进位,所以前面也不可能产生进位
- 末位有进位,在中间位置进位停止,则需要找到进位的典型标志,即位当前位后为0,则前一位加1,直到不为0为止,如
299 -> 300
- 末位有进位,并且一直进位到最前方,导致结果多出一位,例如
9999 -> 10000
。对于这种情况,直接令最高位为1,其他位为0即可
AC代码
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
digits[i]++;
digits[i] %= 10;
if (digits[i] != 0) {
return digits;
}
}
//第三种情况,则需要在开头加上1
digits = new int[digits.length + 1];
digits[0] = 1;
return digits;
}
}
边栏推荐
- 彻底弄清楚session,cookie,sessionStorage,localStorage的区别及应用场景(面试向)
- EZVIZ and Xiaomi compete against smart cameras
- SVN基本操作--文字解析版
- How to uniformly handle error exceptions in embedded C programming?
- 机器学习模型太慢?来看看英特尔(R) 扩展加速
- Categorized input and output, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, go lang basic data types and input and output EP03
- idea installation steps
- 读取SolidWorks文档中的属性,生成PDF(工具开发)
- 上海控安SmartRocket系列产品推介(二):SmartRocket Modeler可视化建模开发工具
- English token preprocessing, used to process English sentences into words
猜你喜欢
随机推荐
人大金仓数据库登录、查看数据库
文档数据库中的文档有什么用呢?
Dubins curve study notes and related thinking
A small test of basic grammar, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, basic grammar of go lang and the use of variables EP02
简单混合运算计算器
MySQL源码解析之执行计划
五、树结构
Flutter Game Tutorial Recreate the famous T-Rex game with Flutter and Flame
关系型数据库的优缺点是什么?
关于振弦采集模块及采集仪振弦频率值准确率的问题
Categorized input and output, Go lang1.18 introductory refining tutorial, from Bai Ding to Hongru, go lang basic data types and input and output EP03
在mysql中,存储过程中参数为中文 乱码解决方案
重载与重写有什么区别?
使用.NET简单实现一个Redis的高性能克隆版(三)
牛客收藏上万的神作!这份阿里P8手写的MySQL主从原理手册真的牛
嵌入式C编程中错误异常该如何统一处理?
What is intrinsic safety?
Thoroughly understand the differences and application scenarios of session, cookie, sessionStorage, and localStorage (interview orientation)
四、哈希表
Oracle ASM磁盘组使用新存储替换旧存储方案