leetcode- Plus One
2016-04-15 13:42
423 查看
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 ,主要考虑极端情况 ,9999999,+1,数组扩展一位;
代码:
package leetcode;
public class PlusOne {
public int[] plusOne(int[] digits) {
int len = digits.length;
int carry = 1;
for(int i = len-1 ; i>=0;i--){
int sum = digits[i] + carry;
if(sum <=9 ) return digits; //只是在最低位+1; 如果有一位不超过9,那么就直接返回,后面的代码都不用执行;
//这里只要考虑极端情况就OK~
digits[i] = 0;
}
int[] newdigits = new int[len+1];
newdigits[0] = 1;
return newdigits; //这个返回的意思是,999999+1 = 1000000,因此,只要在最高位加1位即可,后面的都是0!!
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
The digits are stored such that the most significant digit is at the head of the list.
题意:就是把数字 -> 数组 ,然后个位数 +1 ,主要考虑极端情况 ,9999999,+1,数组扩展一位;
代码:
package leetcode;
public class PlusOne {
public int[] plusOne(int[] digits) {
int len = digits.length;
int carry = 1;
for(int i = len-1 ; i>=0;i--){
int sum = digits[i] + carry;
if(sum <=9 ) return digits; //只是在最低位+1; 如果有一位不超过9,那么就直接返回,后面的代码都不用执行;
//这里只要考虑极端情况就OK~
digits[i] = 0;
}
int[] newdigits = new int[len+1];
newdigits[0] = 1;
return newdigits; //这个返回的意思是,999999+1 = 1000000,因此,只要在最高位加1位即可,后面的都是0!!
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
相关文章推荐
- COMDLL
- CDISC SDTM CM domain 学习笔记
- JSP页面实现servlet过滤器与servlet监听器(JSP中级技术)
- PHP 布尔假值情况
- ORACLE 闪回恢复区(Flashback recovery area)与undo tablespace
- 操作系统实验2-作业调度2.0
- java第五次作业
- leetCode(62)-Reverse Integer
- nfs限定挂载过来以后的用户为本地用户
- 标准OAM注册扩展OAM注册以及扩展OAM报文分析
- MogileFS
- leetCode(62)-Reverse Integer
- leetCode(62)-Reverse Integer
- iOS常用的数学函数
- java 基础加强(myeclipse,debug,junit,JDK5新特性,反射)
- LeetCode 91. Decode Ways
- 读书笔记-神经网络与深度学习(一)-使用神经网络识别手写数字
- 42.leetcode题目:169. Majority Element(还有一种方法待做)
- Spring中的设计模式(转载)
- 我所亲历的北京抢房潮