加一

xiaoxiao2021-02-27  207

/* 问题描述: 给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。该数字按照大小进行排列,最大的数在列表的最前面。 日期:2017-6-23

作者:syt

思路:按位相加,注意进位

*/

#include <iostream> #include <vector> using namespace std; class AddOne{ public: /** * @param digits a number represented as an array of digits * @return the result */ vector<int> plusOne(vector<int>& digits) { // Write your code here bool is = false; int i = digits.size() - 1; digits[i]++; while (i >= 0) { if (is) { digits[i]++; is = false; } if (digits[i] == 10) { if (i == 0) { digits[i] = 1; digits.push_back(0); } else digits[i] = 0; is = true; i--; } else break; } return digits; } };

转载请注明原文地址: https://www.6miu.com/read-13973.html

最新回复(0)