[Java] 2,8,16์ง„์ˆ˜ (parseInt, toBinaryString, ...)

epiphanyยท2022๋…„ 10์›” 28์ผ
0

Programmers School

๋ชฉ๋ก ๋ณด๊ธฐ
17/22
post-thumbnail

๐Ÿ›ซ Programmers School ์ด์ง„์ˆ˜ ๋”ํ•˜๊ธฐ ๋ฌธ์ œ ํ‘ธ๋Š” ๊ณผ์ •์—์„œ ์•Œ๊ฒŒ๋œ ๊ฐœ๋… ์ •๋ฆฌ

๐Ÿ“‘ Code

// Input
//  bin1 = "10"
//  bin2 = "11"
//  result = "101"

class Solution {
    public String solution(String bin1, String bin2) {
        String answer = "";
        int num1 = Integer.parseInt(bin1, 2);
        int num2 = Integer.parseInt(bin2, 2);
        answer = Integer.toBinaryString(num1+num2);
        return answer;
    }
}
  • ๋” ์‰ฝ๊ฒŒ ํ‘ผ ์ฝ”๋“œ
class Solution {
    public String solution(String bin1, String bin2) {
        return Integer.toString(Integer.parseInt(bin1, 2) + Integer.parseInt(bin2, 2),2);
    }
}

๐Ÿงฉ Integer.parseInt()

10์ง„์ˆ˜๋ฅผ 2์ง„์ˆ˜๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ์—ญํ• ์„ ํ•จ
2์ž๋ฆฌ์— 8์„ ๋„ฃ์œผ๋ฉด 8์ง„์ˆ˜, 16์„ ๋„ฃ์œผ๋ฉด 16์ง„์ˆ˜๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Œ

String s = "110";
int n = Integer.parseInt(s, 2);
System.out.print(n);
// output: 6

๐Ÿงฉ Integer.toBinaryString()

10์ง„์ˆ˜๋ฅผ 2์ง„์ˆ˜๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ์—ญํ• 

  • toOctalString - 8์ง„์ˆ˜
  • toHexString - 16์ง„์ˆ˜
int n = 23
String s = Integer.toBinaryString(n);
System.out.print(s);
// output: 10111

๐Ÿ“š Reference

0๊ฐœ์˜ ๋Œ“๊ธ€