【LeetCode】17.Plus One

题目描述(Easy)

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

题目链接

https://leetcode.com/problems/plus-one/description/

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

算法分析

提交代码:

class Solution {
public:
	vector<int> plusOne(vector<int>& digits) {
		const int n = digits.size();
		bool carry = false;

		for (int i = n - 1; i >= 0; --i)
		{
			if ((digits[i] + 1) > 9)
			{
				digits[i] = 0;
				if (i == 0)
					digits.insert(digits.begin(), 1);
			}
			else
			{
				++digits[i];
				break;
			}
		}

		return digits;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& digits, vector<int>& expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	vector<int> result = s.plusOne(digits);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{
	vector<int> matrix = { 1, 2, 3 };
	vector<int> expected = { 1, 2, 4 };
	Test("Test1", matrix, expected);


	matrix = { 4, 3, 2, 1 };
	expected = { 4, 3, 2, 2 };
	Test("Test2", matrix, expected);

	matrix = { 9, 9, 9, 9 };
	expected = { 1, 0, 0, 0, 0 };
	Test("Test3", matrix, expected);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82051989