티스토리 뷰

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


'Programming' 카테고리의 다른 글

[Java] 정규식  (0) 2018.06.12
[Java 문제풀이] LinkedList, removeDuplicate  (0) 2018.05.20
[Java] 문자열  (0) 2018.03.30
[Java 문제풀이] String - Anagram  (0) 2018.03.16
[Java 문제풀이] Arrays: Left Rotation  (0) 2018.03.10
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함