leetcode #66 in cpp
2016-05-31 01:48
351 查看
Solution:
1.start from the tail of the input, and keep adding 1 until we reach the head of the input or the digit + 1 is less than 10.
2.check if the head >= 10. If so insert an extra 1 to the input.
Code:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i = digits.size() - 1;
int carry = 1;
while(carry && i >=0){
digits[i]+=carry;
if(digits[i] >=10){
carry = 1;
digits[i]%=10;
}else carry = 0;
i--;
}
if(carry){
digits.insert(digits.begin(), 1);
}
return digits;
}
};
1.start from the tail of the input, and keep adding 1 until we reach the head of the input or the digit + 1 is less than 10.
2.check if the head >= 10. If so insert an extra 1 to the input.
Code:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i = digits.size() - 1;
int carry = 1;
while(carry && i >=0){
digits[i]+=carry;
if(digits[i] >=10){
carry = 1;
digits[i]%=10;
}else carry = 0;
i--;
}
if(carry){
digits.insert(digits.begin(), 1);
}
return digits;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解