题目
对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。
给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。
示例 1:
输入:A = [1,2,0,0], K = 34
输出:[1,2,3,4]
解释:1200 + 34 = 1234
解释 2:
输入:A = [2,7,4], K = 181
输出:[4,5,5]
解释:274 + 181 = 455
示例 3:
输入:A = [2,1,5], K = 806
输出:[1,0,2,1]
解释:215 + 806 = 1021
示例 4:
输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1
输出:[1,0,0,0,0,0,0,0,0,0,0]
解释:9999999999 + 1 = 10000000000
C++解法
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
int num = K;
int i = (int)A.size() - 1;
int flag = 0;
while (num > 0 || flag > 0) {
int result = flag + (num % 10) + ((i >= 0) ? A[i] : 0);
int actualNumber = result % 10;
flag = (result >= 10);
if (i >= 0) {
A[i] = actualNumber;
} else {
A.insert(A.begin(), actualNumber);
}
num /= 10;
i--;
}
return A;
}
};
int main(int argc, const char * argv[]) {
Solution solution;
vector<int> vec;
int num;
vec = {1, 2, 0, 0};
num = 181;
auto result = solution.addToArrayForm(vec, num);
for (auto item: result) cout << item; cout << endl;
vec = {2, 7, 4};
num = 181;
result = solution.addToArrayForm(vec, num);
for (auto item: result) cout << item; cout << endl;
vec = {2, 1, 5};
num = 806;
result = solution.addToArrayForm(vec, num);
for (auto item: result) cout << item; cout << endl;
vec = {9,9,9,9,9,9,9,9,9,9};
num = 1;
result = solution.addToArrayForm(vec, num);
for (auto item: result) cout << item; cout << endl;
return 0;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-to-array-form-of-integer