CodingReported in a candidate post, Aug 2021
Find number of non-trailing zeroes in binary form of decimal number
Filed under Cisco
Free read 3 of 3Convert the decimal number to its binary string representation using built-in functions.
The question
Given a decimal number, find the count of zeroes in its binary representation, excluding any trailing zeroes (zeroes at the end of the binary string).
Constraints
- Input N: 0 to 2^31 - 1
Examples
- Input
- N = 10
- Output
- 1
- Why
- Binary of 10 is '1010'. The last zero is trailing, so only the middle zero is counted.
- Input
- N = 8
- Output
- 0
- Why
- Binary of 8 is '1000'. All zeroes are trailing, so count is 0.
Approach
Convert the decimal number to its binary string representation using built-in functions.
Find the index of the last '1' in the binary string to determine where non-trailing digits end.
Iterate through the string up to the last '1' and count the occurrences of '0'.
Solution
O(log N) time, O(log N) space
class Solution:
def countNonTrailingZeroes(self, n):
if n == 0: return 0
s = bin(n)[2:]
last_one = s.rfind('1')
return s[:last_one].count('0')
Tips
- What they are testing: Tests bit manipulation and string processing. Pay attention to the definition of 'trailing' and how to identify the last set bit.
- Common mistake: Counting all zeroes instead of stopping at the last '1' or failing to handle N=0 correctly.
Related Cisco questions
Collected from public candidate posts and coding forums. Updated Nov 2026.