LeetCode(29)-Plus One
2016-11-09 00:00
232 查看
题目:
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.
思路:
题意是用一个数组来表示一个非负的整数,范围是0~9的数字,模拟一个加法的加一操作判断是否进位,如果是9,加1就是10,置为0,然后进位。
如果超除了界限,重新设置一个数组,第一位是1,后面是0
-
代码:
public class Solution { public int[] plusOne(int[] digits) { int carries = 1; for(int i = digits.length-1; i>=0 && carries > 0; i--){ // fast break when carries equals zero int sum = digits[i] + 1; digits[i] = sum % 10; carries = sum / 10; } if(carries == 0) return digits; int[] rst = new int[digits.length+1]; rst[0] = 1; for(int i=1; i< rst.length; i++){ rst[i] = 0; } return rst; } }
相关文章推荐
- LeetCode(29)-Plus One
- Leetcode学习(29)—— Plus One
- LeetCode(29)-Plus One
- LeetCode(29)-Plus One
- LeetCode(29)-Plus One
- LeetCode : Plus One
- Leetcode 29. Divide Two Integers
- 2018.3.12 leetcode打卡 #66 plus one
- leetcode_Plus One
- LeetCode编程练习 - Plus One学习心得
- Leetcode-29. Divide Two Integers
- LeetCode 66 Plus One(加一)(vector)
- [LeetCode]29.Divide Two Integers
- [LeetCode] Plus One
- LeetCode_Plus One
- [C++]LeetCode: 29 Maximum Depth of Binary Tree
- leetcode 66. Plus One
- leetcode--Plus One
- leetcode-66. Plus One
- [Leetcode]66. Plus One