본문 바로가기

All Categories/Algorithm

python) int 데이터 타입의 크기 - swift와 코드 비교

반응형

안녕하세요. zhi재희입니다.

leetcode 66. Plus One 을 풀다가, 다른 언어보다 python이 데이터 타입의 크기에 관대하다고 느껴져서 이 글을 쓰게 되었습니다~!

 

66. Plus One
제약 조건

먼저 이 문제는 array로 주어지는 정수에 1을 더하여 arrary로 반환하는 문제입니다.

제약 조건으로는 array의 크기는 1~100이고, arrary의 각 요소는 0~9 사이의 수입니다. (단, 0으로 시작하지 않음)

 

제가 채택한 풀이법은 

1. digit을 reversed로 역순으로 만들어 10의 i(인덱스) 제곱을 한 수를 각 자릿수에 곱해준다.

2. 1을 더한 후 map으로 어레이를 만들어 반환한다.

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        plusOne = 0
        count = len(digits)
        for (i, num) in enumerate(digits):
            plusOne += 10 ** (count - 1 - i) * num
        plusOne += 1
        result = list(map(int, str(plusOne)))
        return result

 

즉, array를 정수로 변환하여 1을 더해주고 다시 array로 만들어 반환했습니다.

 

같은 풀이법에도

swift에서는 Runtime Error,

python, python3 에서는 모두 Accepted , Accepted 가 뜨게 됩니다.

 

왜 이런 차이가 생기는지 알아보겠습니다.

 

Swift

class Solution {
    func plusOne(_ digits: [Int]) -> [Int] {
        var plusOne = 0
        let count = digits.count
        for (i, num) in digits.enumerated() {
            plusOne += NSDecimalNumber(decimal: pow(10, count - 1 - i)).intValue * num
        }
        plusOne += 1
        let result = "\(plusOne)".compactMap { $0.wholeNumberValue}
        return result
    }
}

이와 같이 풀이를 하게 되면 런타임 에러가 나게 됩니다.

 

Swift의 기본 Int type의 크기는 2^64 이기 때문입니다.

제약 조건에서 배열의 크기는 최대 100이기 때문에 런타임 에러가 나게 됩니다.

 

 

python2

python2에서는 런타임 에러가 나지 않는데, 반환하는 리스트의 타입이 정해져 있지 않기 때문입니다.

class Solution(object):
    def plusOne(self, digits):
        plusOne = 0
        count = len(digits)
        for (i, num) in enumerate(digits):
            plusOne += 10 ** (count - 1 - i) * num
        plusOne += 1
        result = list(map(int, str(plusOne)))
        return result

python2에서 int type의 크기는 swift와 동일하게 2^64입니다.

그러나 maxint 값을 벗어나게 되면 long type으로 자동 형 변환을 하게 됩니다.

python 출력 결과

 

따라서 위 코드에서는 64비트 메모리를 벗어나게 되면 long 타입으로 변환되어 처리가 됩니다.

long type은 arbitrary precision을 지원하기 때문에 런타임 에러가 뜨지 않습니다.

 

python3

python3에서는 반환하는 리스트가 int 타입으로 정해져 있습니다.

python3부터 int와 long이 통합되어 int 하나로 쓰이게 되었습니다.

int type은 크기가 무제한으로, arbitrary precision을 지원합니다.

In computer science, arbitrary-precision arithmetic, 
also called bignum arithmetic, multiple-precision arithmetic, or sometimes infinite-precision arithmetic, 
indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. 
This contrasts with the faster fixed-precision arithmetic found in most arithmetic logic unit (ALU) hardware, 
which typically offers between 8 and 64 bits of precision.

arbitrary precision이란 가용 메모리를 유동적으로 운용하여 사용하는 방식입니다.

 

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        plusOne = 0
        count = len(digits)
        for (i, num) in enumerate(digits):
            plusOne += 10 ** (count - 1 - i) * num
        plusOne += 1
        result = list(map(int, str(plusOne)))
        return result

python2와 달리 형변환이 일어나지 않는 것을 알 수 있습니다.

python3 코드
python3 출력 결과

 

감사합니다 :D

반응형