Programming

[Java 문제풀이] Binary Numbers

noonsong 2018. 4. 3. 01:22

출처 : https://www.hackerrank.com/challenges/30-binary-numbers/problem 


문제

Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation.

입력받은 Integer 를 Binary 로 표현했을때, 연속적으로 1이 최대 몇번이 들어갔는지 계산하여 반환하기 


Example

Input : 5 

Output : 1 (5를 바이너리 변환 시 101, 1이 연속 1번)


Input : 13

Output : 2 (13을 바이너리 변환 시 1101, 1이 연속 2번)



문제풀이

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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        
        int remain;
        int max=0;
        int result=0;
        int val = n;
        while(val>0){
                remain = val%2;
                val=val/2;
                if(remain==1 ){
                    max++;  
                    if(result < max){
                    result=max;
                    }
                }else if(remain==0){
                    if(result < max){
                    result=max;
                    }
                    max=0;
                }
        }
        System.out.println(result);
        
    }
}


- Binary 변환 식을 수도코드로 나타내면 아래와 같다. 

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack