Plus One Java
2014-08-28 08:57
211 查看
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.
Idea:
Read digits from back to front
find reminder by % operation
and Carry by / operation
Time: O(N) Space: worst case O(N),normal case O(1)
The digits are stored such that the most significant digit is at the head of the list.
Idea:
Read digits from back to front
find reminder by % operation
and Carry by / operation
Time: O(N) Space: worst case O(N),normal case O(1)
public class Solution { public int[] plusOne(int[] digits) { if(digits.length==0) return digits; int plusOne=1; int carry=0; for (int i=digits.length-1;i>=0;i--){ //reminder % and carray / operation int reminder=(digits[i]+plusOne)%10; carry=(digits[i]+plusOne)/10; //assign new digit to position i digits[i]=reminder; //no carry was found if(carry==0){ return digits; } } //to handle the special case of all digits is number 9 int[] res=new int[digits.length+1]; //need add-on for carry res[0]=1; return res; } }
相关文章推荐
- Plus One leetcode java
- Plus One leetcode java
- LeetCode Plus One Java版解题报告
- 应聘Java笔试时可能出现问题及其答案(第二版Part one)
- JavaOne:JSF的进化——AJAX已经来了
- 微软公司的C#语言可能是Java的灭亡的原因,但Sun公司的ONE则应受到批评
- Memory space manipulating in Java(Section one:Basic Concepts in Java)
- JavaOne 2006 不容错过的十大看点
- JavaOne现场报道(6月10日)
- JAVA组件--电子表格--Formula One e.Spreadsheet Engine
- Memory space manipulating in Java(Section one:Basic Concepts in Java)
- ServeOneSocket.java 服务端源程序
- JavaOne现场报道(6月13日)
- swt、eclipse RCP与“Java All in One”
- JavaOne现场报道(6月12日)
- Afer one week affort for Java
- JavaOne:Sun致力于让Java无所不在
- 有感:应聘Java笔试时可能出现问题及其答案(第二版Part one)
- eclipse+fjep(one-jar)打包java工程为单一的jar
- JavaOne现场报道(6月11日)