Binary Digit Score Problem
#4092
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4092.
You are given two integers a and b.
Let s1 and s2 be the number of set bits in the binary representations of a and b, respectively.
The score of these integers is defined as follows:
- If
s1 >= s2, the score iss1 * s2. - Otherwise, the score is
s2 / s1using integer division.
Return an integer representing the score of a and b.
Example 1:
Input: a = 14, b = 6
Output: 6
Explanation:
- The binary representation of a = 14 is "1110", so s1 = 3.
- The binary representation of b = 6 is "110", so s2 = 2.
- Since s1 > s2, the score of a and b is s1 * s2 = 3 * 2 = 6.
Example 2:
Input: a = 5, b = 15
Output: 2
Explanation:
- The binary representation of a = 5 is "101", so s1 = 2.
- The binary representation of b = 15 is "1111", so s2 = 4.
- Since s1 < s2, the score of a and b is s2 / s1 = 4 / 2 = 2.
Example 3:
Input: a = 10, b = 12
Output: 4
Explanation:
- The binary representation of a = 10 is "1010", so s1 = 2.
- The binary representation of b = 12 is "1100", so s2 = 2.
- Since s1 == s2, the score of a and b is s1 * s2 = 2 * 2 = 4.
Constraints:
1 <= a, b <= 100
Solution
Approach: Count Set Bits
Count the set bits s1 of a and s2 of b. If s1 >= s2 the score is s1 * s2; otherwise it is the integer quotient s2 / s1. Since a >= 1, s1 is at least 1 and the division is safe.
Complexity: O(log a + log b) time, which is O(1) here, and O(1) space.
class Solution:
def calculateScore(self, a: int, b: int) -> int:
s1 = bin(a).count("1")
s2 = bin(b).count("1")
return s1 * s2 if s1 >= s2 else s2 // s1