๊ฐœ๋ฐœ์ผ์ง€

[JAVA] 10์ง„์ˆ˜ → 2์ง„์ˆ˜, format, replace / ๋น„๋ฐ€์ง€๋„ ๋ณธ๋ฌธ

Algorithm

[JAVA] 10์ง„์ˆ˜ → 2์ง„์ˆ˜, format, replace / ๋น„๋ฐ€์ง€๋„

O'mil 2024. 6. 12. 14:35
728x90

๐Ÿ”— ๋งํฌ

[1์ฐจ] ๋น„๋ฐ€์ง€๋„

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ“Œ ๋ฌธ์ œ ์„ค๋ช…

  1. ์ง€๋„๋Š” ํ•œ ๋ณ€์˜ ๊ธธ์ด๊ฐ€ n์ธ ์ •์‚ฌ๊ฐํ˜• ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ, ๊ฐ ์นธ์€ "๊ณต๋ฐฑ" (" ") ๋˜๋Š” "๋ฒฝ" ("#") ๋‘ ์ข…๋ฅ˜๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.
  2. ์ „์ฒด ์ง€๋„๋Š” ๋‘ ์žฅ์˜ ์ง€๋„๋ฅผ ๊ฒน์ณ์„œ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค. ๊ฐ๊ฐ '์ง€๋„ 1'๊ณผ '์ง€๋„ 2'๋ผ๊ณ  ํ•˜์ž. ์ง€๋„ 1 ๋˜๋Š” ์ง€๋„ 2 ์ค‘ ์–ด๋Š ํ•˜๋‚˜๋ผ๋„ ๋ฒฝ์ธ ๋ถ€๋ถ„์€ ์ „์ฒด ์ง€๋„์—์„œ๋„ ๋ฒฝ์ด๋‹ค. ์ง€๋„ 1๊ณผ ์ง€๋„ 2์—์„œ ๋ชจ๋‘ ๊ณต๋ฐฑ์ธ ๋ถ€๋ถ„์€ ์ „์ฒด ์ง€๋„์—์„œ๋„ ๊ณต๋ฐฑ์ด๋‹ค.
  3. '์ง€๋„ 1'๊ณผ '์ง€๋„ 2'๋Š” ๊ฐ๊ฐ ์ •์ˆ˜ ๋ฐฐ์—ด๋กœ ์•”ํ˜ธํ™”๋˜์–ด ์žˆ๋‹ค.
  4. ์•”ํ˜ธํ™”๋œ ๋ฐฐ์—ด์€ ์ง€๋„์˜ ๊ฐ ๊ฐ€๋กœ์ค„์—์„œ ๋ฒฝ ๋ถ€๋ถ„์„ 1, ๊ณต๋ฐฑ ๋ถ€๋ถ„์„ 0์œผ๋กœ ๋ถ€ํ˜ธํ™”ํ–ˆ์„ ๋•Œ ์–ป์–ด์ง€๋Š” ์ด์ง„์ˆ˜์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ’์˜ ๋ฐฐ์—ด์ด๋‹ค.

๐Ÿ‘€ ์˜ˆ์ œ

โœ๏ธ ํ’€์ด ์ˆœ์„œ

  1. 10์ง„์ˆ˜๋ฅผ 2์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ
  2. ๋ณ€ํ™˜ํ•œ 2์ง„์ˆ˜๋ฅผ n์˜ ๊ธธ์ด์— ๋งž์ถ”๊ธฐ
  3. 1 -> "#", 0 -> " "์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ
  4. ์ถœ๋ ฅ

 

๐Ÿ’ป ์ฝ”๋“œ

class Solution {
    public String[] solution(int n, int[] arr1, int[] arr2) {
        String[] answer = new String[n];
        
        for (int i = 0; i < n; i++) {
            String binary = Integer.toBinaryString(arr1[i] | arr2[i]);
            binary = String.format("%" + n + "s", binary);
            binary = binary.replace("1", "#").replace("0", " ");
            answer[i] = binary;
        }
        return answer;
    }
}

 

๐Ÿ“10 ์ง„์ˆ˜ → n์ง„์ˆ˜ ๋ณ€ํ™˜

  • 2์ง„์ˆ˜: toBinaryString(int i)
  • 8์ง„์ˆ˜: toOctalString(int i)
  • 16์ง„์ˆ˜: toHexaString(int i)
  • ๋ฆฌํ„ดํƒ€์ž…์€ ๋ชจ๋‘ String
int num = 10;

String binary = Integer.toBinaryString(num); // 2์ง„์ˆ˜ ๋ณ€ํ™˜
String octal = Integer.toOctalString(num); // 8์ง„์ˆ˜ ๋ณ€ํ™˜
String hexa = Integer.toHexaString(num); // 16์ง„์ˆ˜ ๋ณ€ํ™˜

 

๐Ÿ“ ํฌ๋งท ์ง€์ •์ž

format("%" + n + "s", binary);
String name = "Omil";
int age = 20;

// ๊ฒฐ๊ณผ: "Name: Omil, Age: 30"
String result = String.format("Name: %s, Age: %d", name, age);
System.out.println(result);
  • ์ด๊ฑฐ๋ž‘ ๊ฐ™์€ ๋ฐฉ์‹์ž„
  • ๋‹จ์ง€, ๋ฐ”๊พผ 2์ง„์ˆ˜์˜ ๊ฐ’์ด n์˜ ๊ธธ์ด์™€ ๋‹ค๋ฅผ ๊ฒฝ์šฐ n๊ณผ ๊ธธ์ด๋ฅผ ๋งž์ถฐ์ฃผ๋Š” ๊ฑฐ์ž„
  • %5s: 5์นธ ๋งŒ๋“ค์–ด๋‘๊ณ  ์˜ค๋ฅธ์ชฝ ์ •๋ ฌ
  • %-5s: 5์นธ ๋งŒ๋“ค์–ด๋‘๊ณ  ์™ผ์ชฝ ์ •๋ ฌ

 


๐Ÿ“šReference

https://hianna.tistory.com/527

728x90
Comments