。゚(*´□`)゚。

코딩의 즐거움과 도전, 그리고 일상의 소소한 순간들이 어우러진 블로그

ㅋㅌ

BigInteger

quarrrter 2023. 7. 12. 18:25

int 와 long 범위를 넘어갈 때 사용하는 BigInteger

import java.math.*;

class Solution {
    public String solution(String a, String b) {
        String answer = "";
        
        BigInteger numbera = new BigInteger(a);
        BigInteger numberb = new BigInteger(b);
        BigInteger bigNumber = numbera.add(numberb);
  
        answer = bigNumber.toString();
        return answer;
    }
}
BigInteger numbera = new BigInteger(string or "100");
BigInteger numberb = new BigInteger(string or "100"));
덧셈 (+)
numbera.add(numberb);  
뺄셈 (-)
numbera.subtract(numberb);  
곱셈 (*)
numbera.multiply(numberb); 
나눗셈 (/)
numbera.divide(numberb);  
나머지 (%)
numbera.remainder(numberb); 
int -> BigIntger
BigInteger number = BigInteger.valueOf(900000); 
BigIntger -> int , long, float, double
int_number  = bigNumber.intValue(); 
BigIntger -> String
String_number = bigNumber.toString();

 

https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

 

BigInteger (Java Platform SE 7 )

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevan

docs.oracle.com

 

import java.math.BigInteger;

class Solution {
    public int solution(int balls, int share) {
        if (balls == share || share == 0) {
            return 1;
        }

        BigInteger on = BigInteger.ONE;
        for (int i = balls; i > 0; i--) {
            on = on.multiply(BigInteger.valueOf(i));
        }

        BigInteger b1 = BigInteger.ONE;
        for (int i = balls - share; i > 0; i--) {
            b1 = b1.multiply(BigInteger.valueOf(i));
        }

        BigInteger b2 = BigInteger.ONE;
        for (int i = share; i > 0; i--) {
            b2 = b2.multiply(BigInteger.valueOf(i));
        }

        BigInteger result = on.divide(b1.multiply(b2));
        return result.intValue();
    }
}

BigInteger.ONE은 BigInteger 클래스의 정적 필드(static field)입니다. 이 필드는 값이 1인 BigInteger 객체를 나타냅니다.

BigInteger 클래스는 Java에서 매우 큰 정수를 다룰 수 있도록 지원하는 클래스입니다. 기본 자료형인 int 또는 long으로 표현할 수 있는 범위를 초과하는 정수 값을 다룰 때 BigInteger를 사용할 수 있습니다.

'ㅋㅌ' 카테고리의 다른 글

String.format  (0) 2023.07.14
문자 개수 세기  (0) 2023.07.13
Integer.toBinaryString()  (0) 2023.07.12
빈 배열에 추가, 삭제하기  (0) 2023.07.09
Math  (0) 2023.07.09