如何用Java位运算符判断比特串中1与0数量是否相等并输出?
Got it, let's figure out how to solve this problem where we need to check if the number of 1s and 0s in a binary string (from an integer) are equal—using bitwise operations as much as possible. I’ll build on the code you already have to make this work:
Solution: Check Equal 1s and 0s Count in Binary with Bitwise Operations
First off, let's break down the core logic:
- We can use
BigInteger's built-in bitwise-friendly methods to avoid manual bit manipulation (these methods use low-level bit shifts/masks under the hood, which fits your requirement). - The count of 1s is directly given by
bitCount(). - The count of 0s = total number of bits in the binary string (excluding leading zeros) minus the count of 1s.
- We need to handle edge cases like
0(its binary is just "0", so counts can't be equal) and negative numbers (we'll take the absolute value first since we care about the magnitude's bit string).
Improved Code
import java.math.BigInteger; public class BinaryBitChecker { public void checkEqualBitCounts(int inputNumber) { // Convert to positive BigInteger to handle negatives and zeros BigInteger val = new BigInteger(String.valueOf(inputNumber)).abs(); // Special case: 0's binary is "0" (1 zero, 0 ones) if (val.equals(BigInteger.ZERO)) { System.out.println("Binary: 0 | 1s count: 0, 0s count: 1 | Counts are not equal"); return; } int countOnes = val.bitCount(); // Uses bitwise operations internally int totalBits = val.bitLength(); // Total bits in the minimal binary representation int countZeros = totalBits - countOnes; String binaryString = val.toString(2); // Print out details for clarity System.out.println("Binary string: " + binaryString); System.out.println("Count of 1s: " + countOnes + ", Count of 0s: " + countZeros); // Check and announce result if (countOnes == countZeros) { System.out.println("*Success: Number of 1s and 0s are equal!*"); } else { System.out.println("1s and 0s counts don't match"); } } // Test the method with sample inputs public static void main(String[] args) { BinaryBitChecker checker = new BinaryBitChecker(); checker.checkEqualBitCounts(6); // Binary 110 → 2 ones, 1 zero → not equal checker.checkEqualBitCounts(9); // Binary 1001 → 2 ones, 2 zeros → equal checker.checkEqualBitCounts(-10); // Absolute value is 10 (1010) → equal counts checker.checkEqualBitCounts(0); // Special case → not equal } }
Key Notes
- Bitwise Efficiency:
bitCount()andbitLength()are implemented with optimized bitwise operations (like shifting and masking) in Java'sBigInteger, so this stays true to your request of using bitwise logic for counting. - Edge Case Handling: We explicitly handle
0because its binary representation doesn't have any 1s. For negatives, we take the absolute value since the problem refers to a "bit string" (assuming we care about the magnitude's binary form, not two's complement). - Flexibility: If you need to check fixed-length bit strings (e.g., 8-bit, 16-bit with leading zeros), just replace
totalBitswith your desired fixed length. For example, for 8-bit strings,countZeros = 8 - countOnes.
内容的提问来源于stack exchange,提问作者user9817776
相关产品推荐
相关产品推荐

