LeetCode Plus One
2014-07-04 23:41
357 查看
class Solution { public: vector<int> plusOne(vector<int> &digits) { int carry = 1; int len = digits.size(); vector<int> res; for (int i=len-1; i>=0; i--) { int cur = carry + digits[i]; carry = cur / 10; cur = cur % 10; res.push_back(cur); } if (carry) { res.push_back(1); } reverse(res.begin(), res.end()); return res; } };
水一发
第二轮:
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.
参考了一下题解,对于这个问题不用把数字全部遍历判断完,不需进位时可以直接返回。对多一位数字或者无数字输入的情况处理都统一了。
public class Solution { public int[] plusOne(int[] digits) { int len = digits.length; for (int i=len-1; i>=0; i--) { int d = digits[i]; if (d<9) { digits[i]++; return digits; } else { digits[i] = 0; } } int[] res = new int[len+1]; res[0] = 1; return res; } }
相关文章推荐
- LeetCode 66:Plus One
- LeetCode Plus One Java版解题报告
- Plus One @LeetCode
- LeetCode Plus One
- LeetCode Plus One
- LeetCode66: Plus One
- LeetCode 369. Plus One Linked List(链表加1)
- LeetCode Plus One
- Leetcode 369. Plus One Linked List (Medium) (cpp)
- Leetcode Plus One
- (leetcode)Plus One
- LeetCode(67)Plus One
- Leetcode_plus-one(c++ and python updated)
- Leetcode Plus One
- leetcode Plus One 加一
- LeetCode Plus One
- leetcode Plus One
- LeetCode Plus One
- leetcode Plus One
- LeetCode Plus One