규도자 개발 블로그

[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 10: Binary Numbers 본문

알고리즘/풀이

[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 10: Binary Numbers

규도자 (gyudoza) 2019. 3. 21. 21:12

Objective 
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!

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

Output Format

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

Sample Input 1

5

Sample Output 1

1

Sample Input 2

13

Sample Output 2

2

Explanation

Sample Case 1: 
The binary representation of  is , so the maximum number of consecutive 's is .

Sample Case 2: 
The binary representation of  is , so the maximum number of consecutive 's is .

풀이

#!/bin/python3

import math
import os
import random
import re
import sys



if __name__ == '__main__':
    n = int(input())
    binary = format(n,'b')
    max_consecutive = 0;
    consecutive = 0;
    for number in binary:
        consecutive = consecutive + 1 if int(number) else 0
        max_consecutive = consecutive if max_consecutive < consecutive else max_consecutive
    print(max_consecutive)

설명

주어진 정수를 2진수로 바꾼 다음에 연속되는 1이 최대 몇 개인지 출력하는 문제이다. 예제에서 볼 수 있다시피 주어진 5의 이진수는 101이고 연속되는 최대 1의 갯수는 1개이므로 최종결과는 1이다. 두번째, 13의 이진수는 1101이고 연속되는 최대 1의 갯수는 2개이므로 2가 정답이 되는 것이다.

Comments