www.hackerrank.com/challenges/30-binary-numbers/problem?isFullScreen=true

 

Day 10: Binary Numbers | HackerRank

Find the maximum number of consecutive 1's in the base-2 representation of a base-10 number.

www.hackerrank.com

String binaryNumber = Integer.toBinaryString(num);
String octaNumber = Integer.toOctalString(num);
String hexaNumber = Integer.toHexaString(num);

int num1 = Integer.parseInt(binaryNumber, 2);
int num2 = Integer.parseInt(octaNumber, 8);
int num3 = Integer.parseInt(hexaNumber, 16);

위와 같이 자바는 2진수 8진수 16진수로 만들어주는 메소드가 이미 존재하므로 사용하면 된다.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
        
        String binaryNumber = Integer.toBinaryString(n);
        
        int answer = 0;
        int tempCount = 0;
        
        for(int i=0; i<binaryNumber.length(); i++){
            char tempNum = binaryNumber.charAt(i);
            
            if(tempNum == '1'){
                tempCount++;
                answer = Math.max(tempCount, answer);
            }else{
                tempCount = 0;
            }
        }
        
        System.out.println(answer);

        scanner.close();
    }
}

+ Recent posts