【LeetCode】066.Plus One
2015-03-27 16:18
281 查看
题目:
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.
解答:
考虑进位问题,从后往前遍历,低于9直接加上1并且返回,否则一直往前进位。最高位进位后需要新生成一个数组。
代码:
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.
解答:
考虑进位问题,从后往前遍历,低于9直接加上1并且返回,否则一直往前进位。最高位进位后需要新生成一个数组。
代码:
public class Solution { public int[] plusOne(int[] digits) { if (digits == null || digits.length == 0) return null; int index = digits.length - 1; while (index >= 0) { if (digits[index] < 9) { digits[index] += 1; return digits; } else { digits[index] = 0; index--; } } int[] ret = new int[digits.length + 1]; if (index < 0) { ret[0] = 1; for (int i = 0; i < digits.length; i++) { ret[i + 1] = digits[i]; } } return ret; } }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】
- Leetcode_c++:Plus one(066)
- LeetCode 066 Plus One
- LeetCode066 Plus One
- 【LeetCode】 066. Plus One
- LeetCode 066 Plus One
- Java for LeetCode 066 Plus One
- LeetCode 066 Plus One
- 【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】
- leetcode 066 plus one
- [LeetCode]题解(python):066-Plus One
- LeetCode 066. Plus One
- leetcode解题方案--066--Plus One
- leetcode 066 Plus One(难易度:Easy)
- leetcode 066 —— Plus One
- LeetCode(066) Plus One (Java)
- LeetCode 066 Plus One
- LeetCode 066 Plus one
- LeetCode66——Plus One
- [leetcode]Plus One @ Python