Easy-题目30:66. Plus One
2016-05-30 20:14
344 查看
题目原文:
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)
成绩:
1ms,beats 4.41%,众数:0ms,58.86%
cmershen的碎碎念:
本题巧用了Java的变量初始化,对整形及整形数组的元素,未赋值的均初始化为0.(不像c中还有什么UVF……dts又乱入了)
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又乱入了)
相关文章推荐
- 第六章:堆排序
- apache日志轮询技术(cronolog and rotatelogs)小结
- android中selector在java代码中使用无效的解决方案
- 线性判别函数、判定面以及感知器
- C语言课设-1
- Easy-题目29:26. Remove Duplicates from Sorted Array
- 视图调用控制器的方法
- [JavaScript] 11.JS 偶识【正则表达式】[2]
- 用SharedPreferences存储数据
- 69道Spring面试题和答案
- Easy-题目28:27.Remove Element
- C++独孤九剑第一式——拨云见日(对象内存模型)
- memched1.0源码阅读(2)——基础数据结构
- Easy-题目27:107.Binary Tree Level Order Traversal II
- 深入浅出Mybatis-分页
- jenkins2.6发布tomcat项目
- Java跨域设置
- 存储器管理的基本概念
- shell 修改 JSON文件
- Spring与MongoDB