Python 3实现二进制数减1的字符串函数求助(禁用int()和bin())
int() or bin() Hey there! Let's work through this problem step by step. I see you're stuck on handling cases like 101 (which should become 100) and 100 (which should become 11 once we trim leading zeros) without relying on Python's built-in int() or bin() functions. Let's first break down the core logic of subtracting 1 from a binary number, then fix and build out your code.
The Core Logic of Binary Minus 1
Subtracting 1 from a binary number follows a simple, consistent pattern:
- Start from the rightmost digit and scan left until you find the first
1. - Flip that
1to a0. - Flip all
0s to the right of that digit to1s. - If the entire string is made of
1s (e.g.,111), subtracting 1 will turn all digits to0s except for edge cases like1→0.
Issues in Your Current Code
Looking at your snippet, a few key problems are tripping you up:
if bin == '1'only handles the single-digit case, not longer binary strings.bin.count(0)is invalid (you're trying to count an integer0in a string; it should bebin.count('0')).- You're missing the critical step of traversing from right to left to find the first
1to flip—this is the heart of binary subtraction logic.
Working Solution
Here's a complete function that implements the logic above, with comments explaining each step:
def binary_minus_one(bin_str): # Convert string to a list (strings are immutable in Python, so lists are easier to modify) bin_digits = list(bin_str) length = len(bin_digits) found_one = False # Traverse from the rightmost digit to the left for i in range(length - 1, -1, -1): if bin_digits[i] == '1': # Flip this '1' to '0' bin_digits[i] = '0' found_one = True # Flip all '0's to the right of this digit to '1's for j in range(i + 1, length): bin_digits[j] = '1' break # Convert back to string and clean up leading zeros result = ''.join(bin_digits) # Remove leading zeros (but don't leave an empty string) result = result.lstrip('0') # If result is empty, that means we had all '1's (e.g., '1' → '0') return result if result else '0'
Testing the Function
Let's validate it with your tricky cases and edge scenarios:
binary_minus_one("101")→ Returns"100"(correct: 5 - 1 = 4)binary_minus_one("100")→ Returns"11"(correct: 4 - 1 = 3; leading zero is trimmed for valid binary representation)binary_minus_one("1")→ Returns"0"(correct: 1 - 1 = 0)binary_minus_one("111")→ Returns"110"(correct: 7 - 1 = 6)binary_minus_one("1000")→ Returns"111"(correct: 8 - 1 = 7)
Optional: Preserve Original String Length
If you need to keep the original string length (e.g., 100 → 011 instead of 11), just remove the lstrip('0') and return result if result else '0' lines, and return ''.join(bin_digits) directly.
内容的提问来源于stack exchange,提问作者Elnnaaa

