[ Java ][HackerRank] 30 Days of code Day 10


Day 10: Binary Numbers(이진법)


Task 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.

Input Format

A single integer, .

Constraints

  • 1<= n <=10의6승

Output Format

Print a single base- integer denoting the maximum number of consecutive ‘s in the binary representation of .


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])?");

        int rem=0,s=0,t=0;
        while(n > 0){
            rem = n % 2;
            n = n/2;

            if(rem == 1){
                s++;

                if(s>=t){
                    t = s;
                }
            }else{
                s = 0;
            }
        }
        System.out.println(t);
        scanner.close();
    }
}


while문을 돌려 n이 0보다 클때까지 계속해서 돌려준다.

예를들어 459라는 숫자가 있다고 해보자. 2로 계속 나누고 나누고 나누고… 0이나 1이 될때까지 나눠준다.

나머지가 0이면 하나의 변수인 s가 0이되는거고, (그러면 t의 변동이 없으니 t는 여전히 0)

나머지가 1이면 하나인 변수 s를 1씩 증가시킨다. s가 또 다른 변수인 t보다 크면 t는 s이다.

그러니까 나머지가1이면 s가1이되는데 t는 0 이니까 s는 t보다 크다.

그럴때는 이제 t가 s값을 받아 1이된다.

헤효 근데 제대로 이해한건지 모르겠네…..ㅜㅜ…

그나저나 이진법 십진법이라니.. 중학교떄 배웠는데 엉엉




© 2018. by sora

Powered by sora