Easy-题目30:66. Plus One
来源:互联网 发布:在线美工平台 编辑:程序博客网 时间:2024/06/03 07:27
题目原文:
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运算。数组的头部代表数字的高位。
(例如,数字123用数组[1,2,3]表示,加1运算后返回数组[1,2,4])。
题目分析:
分两种情况考虑。
(1) 这个数字全是9,这是一种最特殊的情况,因为新数组的长度跟原来数组不一样。
(2) 其他情况,则仿照竖式加法,从最后一位开始,寻找第一个不是9的数位(一定存在,否则在情况1中已经解决),这一位加1,后面的数位全部置为0.
源码:(language:java)
public class Solution { public int[] plusOne(int[] digits) { int len=digits.length; if(len==0) return null; boolean all9=true; for(int i=0;i<len;i++) { if(digits[i]!=9) { all9=false; break; } } if(all9) { //this num has the form of 999......... , which will be 1000.... after added 1. int[] result=new int[len+1]; result[0]=1; return result; } else { if(digits[len-1]<9) digits[len-1]++; else { digits[len-1]=0; int i=len-2; while(digits[i]==9) digits[i--]=0; digits[i]++; } return digits; } }}
成绩:
1ms,beats 4.41%,众数:0ms,58.86%
cmershen的碎碎念:
本题巧用了Java的变量初始化,对整形及整形数组的元素,未赋值的均初始化为0.(不像c中还有什么UVF……dts又乱入了)
0 0
- Easy-题目30:66. Plus One
- 66. Plus One (Easy)
- 66. Plus One [easy] (Python)
- 66. Plus One 难度:easy
- Leetcode 66. Plus One (Easy) (cpp)
- Plus One [Easy]
- 5.[easy]Plus one
- [Leetcode 66, Easy] Plus One
- 【LeetCode】(66)Plus One (Easy)
- Easy 66题 Plus One
- Leet Code OJ 66. Plus One [Difficulty: Easy]
- Easy 14 Plus One(66)
- LeetCode-Easy刷题(13) Plus One
- [LeetCode]66.Plus One
- LeetCode --- 66. Plus One
- [Leetcode] 66. Plus One
- [leetcode] 66.Plus One
- 66. Plus One
- android中selector在java代码中使用无效的解决方案
- apache日志轮询技术(cronolog and rotatelogs)小结
- Android小白的培训之路
- 如何将excel表格数据使用图形化工具workbench导入mysql数据库中
- 第六章:堆排序
- Easy-题目30:66. Plus One
- JavaScript学习笔记03
- 二叉树的遍历(递归)
- mysql 锁表解锁
- Web页面请求的历程(四)
- CentOS安装docker
- Easy-题目31:118. Pascal's Triangle
- json对象与json字符串的相互转换
- 获取客户端的代码