[leet code] Plus One
来源:互联网 发布:财报数据下载网站 编辑:程序博客网 时间:2024/06/06 06:52
Given a number represented as an array of digits, plus one to the number.
==============
Analysis:
There are 3 cases of this problem:
1. just add one at the lowest digit, e.g. 123 + 1 = 124.
2. some digits except the hight is 9, e.g. 119 + 1 = 120; 199+1= 200.
3. all the digits are 9, e.g. 9+1 =10, 99+1=100, 999+1=1000.
Accordingly, my idea is the same as manual calculation, add one to the lowest digit, using a variable "plus" to keep if the result is 10, then add this "plus" to the next digit. Continue this process till all the digits in the original array processed.
In order to cope with the 3 case, I introduced a temporary array, length of which is the length of original array + 1 to keep the result. Note that once the array created, length of which cannot be changed.
Finally, I move the result from temporary to the result array (at this time, the result array can be created according the the length of the result).
public class Solution { public int[] plusOne(int[] digits) { int length = digits.length; if(length == 0) return digits; // add one to original number, and store the result in to new array <- length of new array = length of original array +1 int plus = 0; int[] temp = new int[length+1]; for(int i=length-1; i>=0; i--){ int sum = 0; if(i == length-1) sum = digits[i]+1;// the 1st time else sum = digits[i] + plus; plus = sum/10; temp[length-1-i] = sum%10; if(i==0 && plus ==1) temp[length] = 1; //the highest digit } int newLength = 0; if(temp[length] == 1) newLength = length+1; else newLength = length; int[] rs = new int[newLength]; for (int i=0; i<newLength; i++){ rs[i] = temp[newLength-i-1]; } return rs; }}
Remark: my approach might not look elegant, but I believe it's strait foreword, and the time complexity is not too bad, O(2n).
- [leet code] Plus One
- Leet -- Plus One
- Leet Code OJ 66. Plus One [Difficulty: Easy]
- CODE 65: Plus One
- leetcode 日经贴,Cpp code -Plus One
- [leet code] Gray Code
- [leet code] Same Tree
- [leet code] Reverse Integer
- [leet code] Remove Element
- [leet code] Maximum Subarray
- [leet code] Climbing Stairs
- [leet code] Symmetric Tree
- [leet code] Permutations
- [leet code] Generate Parentheses
- [leet code] Sort Colors
- [leet code] Unique Paths
- [leet code] Rotate Image
- [leet code] Path Sum
- Object-C 中的虚函数的学习记录
- 小强的HTML5移动开发之路(26)—— JavaScript回顾1
- LeetCode - Convert Sorted Array to Binary Search Tree
- LeetCode(145)Binary Tree Postorder Traversal
- LeetCode - Merge Sorted Array
- [leet code] Plus One
- HowTo: Use cat Command In Linux / UNIX
- Head First Java_Study Notes_Chapter 5 Extra-Strength Methods
- 【DP】 wordbreak2 仿照神的代码
- 2014年春运大幕明日拉开 客运量达36.23亿人次
- [leet code] Container With Most Water
- C# WinForm开发系列 - ListBox/ListView/Panel
- What is BranchCache?
- Myeclipse 2014JAX-WS Web Services & Clients备忘