0
0

More than 1 year has passed since last update.

Leetcode 989. Add to Array-Form of Integer

Last updated at Posted at 2023-02-15

アプローチ

Brute-force

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

class Solution {
    // アプローチが悪い
    public List<Integer> addToArrayForm1(int[] num, int k) {

        StringBuilder sb = new StringBuilder();
        for (int n : num) {
            sb.append(n);
        }

        System.out.println(sb);
        BigDecimal tempBigDecimal = new BigDecimal(sb.toString());

        BigDecimal tempK = new BigDecimal(k);


        tempBigDecimal = tempBigDecimal.add(tempK);
        List<Integer> result = new ArrayList<>();

        for (char c : tempBigDecimal.toString().toCharArray()) {
            result.add(Integer.parseInt("" + c));
        }
        return result;
        
    }

    public List<Integer> addToArrayForm(int[] num, int k) {
        List<Integer> result = new ArrayList<>();

        int i = num.length - 1;

        int value = 0;
        int digitSum = 0;
        int carry = 0;

        while (i >= 0 || k > 0 || carry > 0) {
            digitSum = carry;
            if (i >= 0) {
                digitSum += num[i--];
            }
            if (k > 0) {
                digitSum += k % 10;
            }
            result.add(digitSum % 10);
            k /= 10;
            carry = digitSum / 10;
        }

        Collections.reverse(result);


        return result;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0