Similar Problems
Similar Problems not available
Convert To Base 2 - Leetcode Solution
Companies:
LeetCode: Convert To Base 2 Leetcode Solution
Difficulty: Medium
Topics: math
The problem "Convert to Base 2" on LeetCode asks us to convert a given positive integer into its binary representation using the base 2 system.
To solve this problem, we need to first understand how the binary system works. In the binary system, each digit can only have two possible values, 0 or 1. The value of each digit is determined by its position, where the rightmost position holds the value of 2^0 (1), the second-rightmost position holds the value of 2^1 (2), and so on. For example, the number 1011 in binary system represents the value 12^3 + 02^2 + 12^1 + 12^0 = 11 in the decimal system.
One approach to solve this problem is to use the division-by-2 algorithm. This algorithm repeatedly divides the given number by 2 and keeps track of the remainders. The binary representation is obtained by reversing the order of the remainders. Here's some sample Python code that implements this algorithm:
def toBinary(n: int) -> str:
binary = ''
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n //= 2
return binary if binary else '0'
In this code, we first initialize an empty string binary
to store the binary representation of the number. We then enter a while loop that repeats until the number n
becomes 0. In each iteration, we calculate the remainder of the division of n
by 2, append it to the left of the binary
string, and update the value of n
by dividing it by 2 using the floor division operator //
. Finally, we return the binary
string if it's not empty, otherwise we return the string '0'
.
We can test the function with some example inputs:
>>> toBinary(2)
'10'
>>> toBinary(3)
'11'
>>> toBinary(10)
'1010'
>>> toBinary(255)
'11111111'
This solution has a time complexity of O(log n) because we need to perform a logarithmic number of iterations corresponding to the number of digits in the binary representation of n
.
Convert To Base 2 Solution Code
1