LeetCode 之 Plus One — C 实现
2015-06-11 16:37
465 查看
Plus One
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.
给定一个数字数组组成的非负整数,给该数加 1.
整数的高位存储在表头位置。
分析:
注意进位和最高位是否有进位,如果最高位有进位,则需要重新分配一个新节点存储,数字长度也要加 1。
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int sum = 0;
int index = 0;
int carry = 0;
int *newdigits = NULL;
if(!digits || digitsSize == 0)/*空指针或空数组*/
{
*returnSize = 0;
return digits;
}
*returnSize = digitsSize;
index = digitsSize - 1;
while(index >= 0)
{
sum = (index == digitsSize-1)?(digits[index] + 1 + carry):(digits[index] + carry);
digits[index] = sum % 10;
carry = sum / 10;
if(carry == 0)
{
return digits;
}
--index;
}
if(carry) /*最高位有进位*/
{
*returnSize = digitsSize + 1;
newdigits = (int *)malloc((digitsSize + 1)*sizeof(int));
newdigits[0] = carry;
for(index = 0; index < digitsSize; ++index)
{
newdigits[index+1] = digits[index];
}
return newdigits;
}
return digits;
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [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[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)