Algorithm & Data Structures/Programers

Lv 2. 다음 큰 숫자

Geisha 2024. 4. 15. 09:52

 

문자열에 포함된 1의 갯수가 몇개인지 파악하는 과정에서 상당한 귀찮음이 예상되었는데

replace 함수를 사용하니 훨씬더 간단하고 편했다. 

import java.io.*;
import java.util.*;

class Solution {
    public int solution(int n) {
        int answer = 0;
        boolean find = false;
        answer = n;
        int count = 0,anscnt;
        count = Integer
            .toBinaryString(n)
            .replace("0","")
            .length();
        while(true){
            if(find) break;
            answer += 1; 
            anscnt = Integer
                .toBinaryString(answer)
                .replace("0","")
                .length();
            if(count==anscnt){
                find = true;
            }
            
        }
        
        return answer;
    }
}

 

String.replace("target","to");