【Leetcode】66. Plus One

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.

给定一个数组,使其称为一个整数,然后返回那个整数+1之后的各位存储的数组

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

class Solution {
public:
	vector<int> plusOne(vector<int>& digits) {
	//把最后一位加一然后判断,如果有进位,前一位加一,如果还是10,,最后如果第一位也是要进位,那么就从头加一位
		auto ans = digits;  //copy原来的vector,防止有大数,位数过多,不能进行,long16/32位 longlong 32/64 2^16
		for(int i = digits.size()-1; i >= 0; ){
			//先把最后一位加1
			ans[i]++;
			//判断当前最后一位加完后,如果是10,那么赋成0,i左移,不是,就直接输出这个vector
			if((ans[i] == 10)&&i != 0){
				ans[i] = 0;
				i = i - 1;
				
			}
			else if((ans[i] == 10) && (i == 0)){
				ans[i] = 0;
				ans.insert(ans.begin(), 1);
				i = -1;
			}else if(ans[i] != 10){
				return ans;
			}
			
			}
		
		return ans;
		
	}
};

猜你喜欢

转载自blog.csdn.net/zerlina98/article/details/80150761