66. Plus One

2018/04/08 leetcode 共 582 字,约 2 分钟

Title

the problem link

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

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

The digits are stored such that the most significant digit is at the head of the list.

Solution

大整数运算,就是一个int数组加1后,模拟大整数加1

//cpp:
class Solution {
public:
	vector<int> plusOne(vector<int>& digits) {
		int t = 1;
		for (int i = digits.size() - 1; i >= 0; i--) {
			if (t == 0) break;
			int sum = digits[i] + t;
			digits[i] = sum % 10;
			t = sum / 10;
			cout << t << endl;
		}
		if (t > 0) {
			digits.insert(digits.begin(), t);
		}
		return digits;
	}
};

Search

    Table of Contents