当前位置:网站首页>【日常训练】66. 加一
【日常训练】66. 加一
2022-07-01 21:47:00 【Puppet__】
题目
给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 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
代码
package dayLeetCode;
public class dayleetcode66 {
/** * 关键是处理9 * (1)最后一位不是9的话,直接+1 * (2)最后几位都是9的话,找到从后往前第一个非9的元素,将其+1,并将其后的9全部置0 * (3)全部是9的话,扩位,最前面加个1 * @param digits * @return */
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i = n -1; i >= 0 ; i--) {
if (digits[i] != 9){
digits[i]++;
for (int j = i + 1; j < n; j++){
digits[j] = 0;
}
return digits;
}
}
digits = new int[n + 1];
digits[0] = 1;
return digits;
}
public static void main(String[] args) {
dayleetcode66 obj = new dayleetcode66();
System.out.println(obj.plusOne(new int[]{
1, 2, 3}));
}
}
边栏推荐
- "The silk road is in its youth and looks at Fujian" is in the hot collection of works in the Fujian foreign youth short video competition
- Go - exe corresponding to related dependency
- 指标陷阱:IT领导者易犯的七个KPI错误
- 20220701
- Little p weekly Vol.11
- Mysql——》MyISAM存储引擎的索引
- What is the difference between PMP and NPDP?
- [STM32] stm32cubemx tutorial II - basic use (new projects light up LED lights)
- [intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial
- Separate the letters and numbers in the string so that the letters come first and the array comes last
猜你喜欢
Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
Object memory layout
Pytorch sharpening chapter | argmax and argmin functions
【MySQL】explain的基本使用以及各列的作用
One of the basic learning of function
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
【juc学习之路第9天】屏障衍生工具
keras训练的H5模型转tflite
Indicator trap: seven KPI mistakes that it leaders are prone to make
Flume interview questions
随机推荐
Getting started with the lockust series
What is the difference between consonants and Initials? (difference between initials and consonants)
MySQL数据库详细学习教程
详解ThreadLocal
Aidl basic use
Introduction and download of the latest version of airserver2022
GaussDB(DWS)主动预防排查
配置筛选机
牛客月赛-分组求对数和
Mask wearing detection method based on yolov5
IDA动态调试apk
flink sql 命令行 连接 yarn
【JetCache】JetCache的使用方法与步骤
flink sql-client 使用 对照并熟悉官方文档
The correct way to set the bypass route
使用闭包实现点击按钮切换 toggle
比较版本号[双指针截取自己想要的字串]
Yyds dry goods inventory # solve the real problem of famous enterprises: egg twisting machine
快乐数[环类问题之快慢指针]
【目标跟踪】|单目标跟踪指标