Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a non-negative integer n.
A non-negative integer is called binary-palindromic if its binary representation (written without leading zeros) reads the same forward and backward.
Return the number of integers k such that 0 <= k <= n and the binary representation of k is a palindrome.
Note: The number 0 is considered binary-palindromic, and its representation is "0".
Example 1:
Input: n = 9
Output: 6
Explanation:
The integers k in the range [0, 9] whose binary representations are palindromes are:
0 → "0"1 → "1"3 → "11"5 → "101"7 → "111"9 → "1001"All other values in [0, 9] have non-palindromic binary forms. Therefore, the count is 6.
Example 2:
Input: n = 0
Output: 1
Explanation:
Since "0" is a palindrome, the count is 1.
Constraints:
0 <= n <= 1015Problem summary: You are given a non-negative integer n. A non-negative integer is called binary-palindromic if its binary representation (written without leading zeros) reads the same forward and backward. Return the number of integers k such that 0 <= k <= n and the binary representation of k is a palindrome. Note: The number 0 is considered binary-palindromic, and its representation is "0".
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Bit Manipulation
9
0
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func countBinaryPalindromes1(n int64) int {
// s := strconv.FormatUint(uint64(n), 2)
// m := len(s)
//
// // 二进制长度小于 m,随便填
// ans := 1
// // 枚举二进制长度,最高位填 1,回文数左半的其余位置随便填
// for i := 1; i < m; i++ {
// ans += 1 << ((i - 1) / 2)
// }
//
// var dfs func(int, int, bool) int
// dfs = func(i, pal int, limit bool) (res int) {
// if !limit {
// // 回文数左半的其余位置随便填
// return 1 << ((m+1)/2 - i)
// }
//
// if i == (m+1)/2 {
// // 左半反转到右半
// // 如果 m 是奇数,那么去掉回文中心再反转
// for v := pal >> (m % 2); v > 0; v /= 2 {
// pal = pal*2 + v%2
// }
// if pal > int(n) {
// return 0
// }
// return 1
// }
//
// up := int(s[i] - '0')
// for d := 0; d <= up; d++ {
// res += dfs(i+1, pal*2+d, limit && d == up)
// }
// return res
// }
//
// // 最高位一定是 1,从 i=1 开始填
// return ans + dfs(1, 1, true)
// }
//
// func countBinaryPalindromes(n int64) int {
// if n == 0 {
// return 1
// }
//
// m := bits.Len(uint(n))
// k := (m - 1) / 2
//
// // 二进制长度小于 m
// ans := 2<<k - 1
// if m%2 == 0 {
// ans += 1 << k
// }
//
// // 二进制长度等于 m,且回文数的左半小于 n 的左半
// left := n >> (m / 2)
// ans += int(left) - 1<<k
//
// // 二进制长度等于 m,且回文数的左半等于 n 的左半
// right := bits.Reverse32(uint32(left>>(m%2))) >> (32 - m/2)
// if left<<(m/2)|int64(right) <= n {
// ans++
// }
//
// return ans
// }
// Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
package main
import (
"math/bits"
"strconv"
)
// https://space.bilibili.com/206214
func countBinaryPalindromes1(n int64) int {
s := strconv.FormatUint(uint64(n), 2)
m := len(s)
// 二进制长度小于 m,随便填
ans := 1
// 枚举二进制长度,最高位填 1,回文数左半的其余位置随便填
for i := 1; i < m; i++ {
ans += 1 << ((i - 1) / 2)
}
var dfs func(int, int, bool) int
dfs = func(i, pal int, limit bool) (res int) {
if !limit {
// 回文数左半的其余位置随便填
return 1 << ((m+1)/2 - i)
}
if i == (m+1)/2 {
// 左半反转到右半
// 如果 m 是奇数,那么去掉回文中心再反转
for v := pal >> (m % 2); v > 0; v /= 2 {
pal = pal*2 + v%2
}
if pal > int(n) {
return 0
}
return 1
}
up := int(s[i] - '0')
for d := 0; d <= up; d++ {
res += dfs(i+1, pal*2+d, limit && d == up)
}
return res
}
// 最高位一定是 1,从 i=1 开始填
return ans + dfs(1, 1, true)
}
func countBinaryPalindromes(n int64) int {
if n == 0 {
return 1
}
m := bits.Len(uint(n))
k := (m - 1) / 2
// 二进制长度小于 m
ans := 2<<k - 1
if m%2 == 0 {
ans += 1 << k
}
// 二进制长度等于 m,且回文数的左半小于 n 的左半
left := n >> (m / 2)
ans += int(left) - 1<<k
// 二进制长度等于 m,且回文数的左半等于 n 的左半
right := bits.Reverse32(uint32(left>>(m%2))) >> (32 - m/2)
if left<<(m/2)|int64(right) <= n {
ans++
}
return ans
}
# Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
#
# @lc app=leetcode id=3677 lang=python3
#
# [3677] Count Binary Palindromic Numbers
#
# @lc code=start
class Solution:
def countBinaryPalindromes(self, n: int) -> int:
if n == 0:
return 1
s = bin(n)[2:]
length = len(s)
ans = 1 # Start with 1 because 0 is always a binary palindrome
# 1. Count all palindromes with length < length of n
for l in range(1, length):
# The first bit must be 1. The palindrome is determined by the first ceil(l/2) bits.
# Since the first bit is fixed to 1, we have ceil(l/2) - 1 bits to choose freely.
count = 1 << ((l + 1) // 2 - 1)
ans += count
# 2. Count palindromes with length == length of n
# Number of bits determining the palindrome
half_len = (length + 1) // 2
# The prefix of n that determines the palindrome shape
prefix_str = s[:half_len]
prefix_val = int(prefix_str, 2)
# The smallest valid prefix for this length starts with 1 followed by zeros
# It corresponds to 1 << (half_len - 1)
min_prefix_val = 1 << (half_len - 1)
# All prefixes from min_prefix_val to prefix_val - 1 form valid palindromes < n
if prefix_val > min_prefix_val:
ans += (prefix_val - min_prefix_val)
# 3. Check the palindrome formed by prefix_str itself
# Construct the palindrome
left_part = prefix_str
if length % 2 == 1:
# Odd length: e.g., prefix "10", len 3 -> "10" + "1" = "101"
right_part = left_part[:-1][::-1]
else:
# Even length: e.g., prefix "10", len 4 -> "10" + "01" = "1001"
right_part = left_part[::-1]
candidate_str = left_part + right_part
candidate_val = int(candidate_str, 2)
if candidate_val <= n:
ans += 1
return ans
# @lc code=end
// Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (go):
// // Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func countBinaryPalindromes1(n int64) int {
// s := strconv.FormatUint(uint64(n), 2)
// m := len(s)
//
// // 二进制长度小于 m,随便填
// ans := 1
// // 枚举二进制长度,最高位填 1,回文数左半的其余位置随便填
// for i := 1; i < m; i++ {
// ans += 1 << ((i - 1) / 2)
// }
//
// var dfs func(int, int, bool) int
// dfs = func(i, pal int, limit bool) (res int) {
// if !limit {
// // 回文数左半的其余位置随便填
// return 1 << ((m+1)/2 - i)
// }
//
// if i == (m+1)/2 {
// // 左半反转到右半
// // 如果 m 是奇数,那么去掉回文中心再反转
// for v := pal >> (m % 2); v > 0; v /= 2 {
// pal = pal*2 + v%2
// }
// if pal > int(n) {
// return 0
// }
// return 1
// }
//
// up := int(s[i] - '0')
// for d := 0; d <= up; d++ {
// res += dfs(i+1, pal*2+d, limit && d == up)
// }
// return res
// }
//
// // 最高位一定是 1,从 i=1 开始填
// return ans + dfs(1, 1, true)
// }
//
// func countBinaryPalindromes(n int64) int {
// if n == 0 {
// return 1
// }
//
// m := bits.Len(uint(n))
// k := (m - 1) / 2
//
// // 二进制长度小于 m
// ans := 2<<k - 1
// if m%2 == 0 {
// ans += 1 << k
// }
//
// // 二进制长度等于 m,且回文数的左半小于 n 的左半
// left := n >> (m / 2)
// ans += int(left) - 1<<k
//
// // 二进制长度等于 m,且回文数的左半等于 n 的左半
// right := bits.Reverse32(uint32(left>>(m%2))) >> (32 - m/2)
// if left<<(m/2)|int64(right) <= n {
// ans++
// }
//
// return ans
// }
// Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3677: Count Binary Palindromic Numbers
// package main
//
// import (
// "math/bits"
// "strconv"
// )
//
// // https://space.bilibili.com/206214
// func countBinaryPalindromes1(n int64) int {
// s := strconv.FormatUint(uint64(n), 2)
// m := len(s)
//
// // 二进制长度小于 m,随便填
// ans := 1
// // 枚举二进制长度,最高位填 1,回文数左半的其余位置随便填
// for i := 1; i < m; i++ {
// ans += 1 << ((i - 1) / 2)
// }
//
// var dfs func(int, int, bool) int
// dfs = func(i, pal int, limit bool) (res int) {
// if !limit {
// // 回文数左半的其余位置随便填
// return 1 << ((m+1)/2 - i)
// }
//
// if i == (m+1)/2 {
// // 左半反转到右半
// // 如果 m 是奇数,那么去掉回文中心再反转
// for v := pal >> (m % 2); v > 0; v /= 2 {
// pal = pal*2 + v%2
// }
// if pal > int(n) {
// return 0
// }
// return 1
// }
//
// up := int(s[i] - '0')
// for d := 0; d <= up; d++ {
// res += dfs(i+1, pal*2+d, limit && d == up)
// }
// return res
// }
//
// // 最高位一定是 1,从 i=1 开始填
// return ans + dfs(1, 1, true)
// }
//
// func countBinaryPalindromes(n int64) int {
// if n == 0 {
// return 1
// }
//
// m := bits.Len(uint(n))
// k := (m - 1) / 2
//
// // 二进制长度小于 m
// ans := 2<<k - 1
// if m%2 == 0 {
// ans += 1 << k
// }
//
// // 二进制长度等于 m,且回文数的左半小于 n 的左半
// left := n >> (m / 2)
// ans += int(left) - 1<<k
//
// // 二进制长度等于 m,且回文数的左半等于 n 的左半
// right := bits.Reverse32(uint32(left>>(m%2))) >> (32 - m/2)
// if left<<(m/2)|int64(right) <= n {
// ans++
// }
//
// return ans
// }
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.