BASHA TECH
[HackerRank][Python] Binary Numbers 본문
Task
Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's n's binary representation. When working with different bases, it is common to show the base as a subscript.
Example
n = 125
The binary representation of decimal number 125 is binary number 1111101. In base 10, there are 5 and 1 consecutive ones in two groups. Print the maximum, 5.
Input Format
A single integer, n.
Constraints
- 1 <= n <= 10^6
Output Format
Print a single base-10 integer that denotes the maximum number of consecutive 1's in the binary representation of n.
#!/bin/python3
import math
import os
import random
import re
import sys
def maxConsecutiveOnes(n):
#convert n to binary
binary = bin(n)[2:]
#count consecutive ones
max_count = 0
count = 0
for digit in binary:
if digit == '1':
count += 1
else :
max_count = max(max_count, count)
count = 0
max_count = max(max_count, count)
return max_count
if __name__ == '__main__':
n = int(input().strip())
result = maxConsecutiveOnes(n)
print(result)
The maxConsecutiveOnes() function takes an integer n as input and returns the maximum number of consecutive ones in the binary representation of n.
The bin() function is used to convert n to a binary string. We then iterate through the string, keeping track of the current count of consecutive ones (count) and the maximum count seen so far (max_count). Whenever we encounter a zero, we update max_count if necessary and reset count to zero. Once we've finished iterating through the string, we update max_count one final time and return it.
In the main block, we simply take input for n, call the maxConsecutiveOnes() function, and print the result.
'Activity > Coding Test' 카테고리의 다른 글
[HackerRank][Python] Inheritance (0) | 2023.04.24 |
---|---|
[HackerRank][Python] 2D Arrays (0) | 2023.04.24 |
[HackerRank][Python] Recursion 3 (0) | 2023.04.17 |
[HackerRank][Python] Dictionaries and Maps (0) | 2023.04.17 |
[HackerRank][Python] Arrays (0) | 2023.04.17 |