๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹ค์Œ ํฐ ์ˆซ์ž

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹ค์Œ ํฐ ์ˆซ์ž

https://programmers.co.kr/learn/courses/30/lessons/12911

๋ฌธ์ œ ์ ‘๊ทผ

์ฒ˜์Œ์— ์ ‘๊ทผํ•  ๋•Œ๋Š” Integer.toBinaryString() ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ stringํ˜•ํƒœ์˜ 2์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•œ ํ›„ 1์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ณ , n+1๋ถ€ํ„ฐ 1์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ™์„ ๋•Œ๊นŒ์ง€ while๋ฌธ์„ ๋Œ๋ ธ๋‹ค.
๋‹ค ํ’€๊ณ  ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ๊นŒ Integer.countBit()๋ฅผ ์ด์šฉํ•˜๋ฉด 1์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด์„œ ๋” ์‰ฝ๊ฒŒ ํ’€์—ˆ๋‹ค.

Code

Integer.toBinaryString()์ด์šฉํ•œ ํ’€์ด

class Solution {
    public int solution(int n) {
        String binaryNum = Integer.toBinaryString(n);
        int oneCnt = countOne(binaryNum);
        int newCnt = -1;
        int newNum = n;
        while(oneCnt != newCnt){
            newNum++;
            newCnt = countOne((Integer.toBinaryString(newNum)));
        }
        return newNum;
    }

    public int countOne(String str){
        int cnt = 0;
        for(char ch: str.toCharArray()){
            if(ch == '1') cnt++;
        }
        return cnt;
    }
}

Integer.bitCount()์ด์šฉํ•œ ํ’€์ด

class Solution {
    public int solution(int n) {
        int oneCnt = Integer.bitCount(n);
        int newCnt = -1;
        int newNum = n;
        while(oneCnt != newCnt){
            newNum++;
            newCnt = Integer.bitCount(newNum);
        }
        return newNum;
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

์ •๋ง ์œ ์šฉํ•œ ํ•จ์ˆ˜๋“ค์ด ๋„ˆ๋ฌด ๋งŽ๋‹ค... ์˜ค๋Š˜๋„ ์ด๋ ‡๊ฒŒ bitCount๋ฅผ ๋ฐฐ์›Œ๊ฐ„๋‹ค...

๋ฐ˜์‘ํ˜•