티스토리 뷰

leetcode.com/problems/add-to-array-form-of-integer/

 

Add to Array-Form of Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 


  • 문제

전달한 한자리수 숫자를 담고있는 num배열과 k숫자를 더한 결과를 한자리수 배열로 만들어라

 

 

  • 어떻게 풀까?

num배열로 받은 한자리 숫자 배열을 붙여서 숫자로 만든다. -> [1,2,3] = 123

k와 num배열로 만든 숫자를 더한다음 스트링으로 만든다.

스트링에서 한캐릭터씩 가져와서 배열을 만들어 리턴!

 

 

  • 구현 중 만난 문제/해결

stream을 사용해서 풀려고 했다.

char - '0'을 사용해 character 숫자를 int숫자로 변경하는 방식을 사용했다. 

-> '1' - '0'을 하게될 경우 '1'이 아스키코드로 49이고 '0'이 48이라 1로 된다.

-> chars, shorts, bytes는 더하면 int결과가됨

 

char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK -> The result of the binary operation is converted to the type of the left-hand variable

 

 

long을 사용해서 틀리다가 bitInteger타입을 사용해 문제를 풀 수 있었다.

 

byte -> 1 byte = 8 bits -> -128 ~ 127 (2의 8승은 256이며, 이걸 2로 나눈것. 양수와 0표시하여 127까지)

short -> 2 bytes = 16bits -> -32,768~32,767

int -> 4 bytes = 32 bits -> -2,147,483,648 ~ 2,147,483,647

long -> 16 bytes = 64 bits -> -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807

<각 범위를 벗어나는 경우 0으로 출력됨>

 

BigInteger -> 문자열 형태로 이루어져 있어 숫자의 범위가 무한하기에 어떠한 숫자이든지 담을 수 있음

 

번외 )

short sh = 'c';

System.out.println(sh);

-> 99가 리턴됨.  'c'는 short인 sh범위를 넘지 않기 때문에 문제가 없음. 

'c'나 99를  저장하든 메모리에는 0000000001000011가 들어가게되어서.

 

 

  • 구현

 

 

import java.util.*;
import java.math.BigInteger;
class Solution {
    public List<Integer> addToArrayForm(int[] num, int k) {
        Optional<String> str = Arrays.stream(num)
                .mapToObj(String::valueOf)
                .reduce((x, y) -> x + y);

        BigInteger bigInteger = new BigInteger(str.get());
        BigInteger resultNum = bigInteger.add(BigInteger.valueOf(k));
        String temp = resultNum.toString();

        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < temp.length(); i++)
        {
            result.add(temp.charAt(i) - '0');
        }

        return result;
    }
}

 

 

번외 참고: imasoftwareengineer.tistory.com/48

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함