For a non-negative integer x, the array-form of
Given the array-form
X
is an array of its digits in left to right order. For example, if X = 1231
, then the array form is [1,2,3,1]
.Given the array-form
A
of a non-negative integer X
, return the array-form of the integer X+K
.Example 1:
Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class AddArrayInteger {public static void main(String[] args) {int[] A = { 1, 2, 0, 0 };int K = 34;List<Integer> arr = addToArrayForm(A, K);System.out.println(Arrays.asList(arr));}static List<Integer> addToArrayForm(int[] A, int K) {int n = A.length, carry = 0;List<Integer> res = new ArrayList<Integer>();for (int i = n - 1; i >= 0; i--) {res.add((carry + A[i] + K % 10) % 10);carry = (carry + A[i] + K % 10) / 10;K = K / 10;}if (K > 0) {while (K > 0) {res.add((K % 10 + carry) % 10);carry = (carry + K % 10) / 10;K = K / 10;}}if (carry > 0)res.add(carry);Collections.reverse(res);return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> addToArrayForm(vector<int> &A, int K){int n = A.size(), carry = 0;vector<int> res;for (int i = n - 1; i >= 0; i--){res.push_back((carry + A[i] + K % 10) % 10);carry = (carry + A[i] + K % 10) / 10;K = K / 10;}if (K > 0){while (K){res.push_back((K % 10 + carry) % 10);carry = (carry + K % 10) / 10;K = K / 10;}}if (carry > 0)res.push_back(carry);reverse(res.begin(), res.end());return res;}int main(){vector<int> A = {1, 2, 0, 0};int K = 34;vector<int> arr = addToArrayForm(A, K);cout << "[";for (int i = 0; i < arr.size() - 1; i++)cout << arr[i] << ",";cout << arr[arr.size() - 1] << "]";return 0;}
No comments:
Post a Comment