Flipping bits

  • + 0 comments

    Java - How can I look at a problem and find the most simple solution? Is there a guideline on what to think about before coding. For example, logical operators first?

        public static long flippingBits(long n) {
            // Convert to binary
            long q = n;
            String binary = "";
    
            while (q > 0) {
                long remainder = q % 2;
                binary = remainder + binary;
                q = q / 2;
            }
            System.out.println("Binary of " + n + " = " + binary);
    
            // Calculate how many zeros to add at the start to get 32-bit
            int zerosToAdd = 32 - binary.length();
            String paddedBinary = "0".repeat(zerosToAdd) + binary;
            System.out.println("32-bit padded: " + paddedBinary);
    
            // Flip the bits
            StringBuilder flipped = new StringBuilder();
            for (int i = 0; i < paddedBinary.length(); i++) {
                if (paddedBinary.charAt(i) == '0') {
                    flipped.append('1');
                } else {
                    flipped.append('0');
                }
            }
    
            // Convert StringBuilder to String
            String flippedStr = flipped.toString();
    
            // Parse as base-2
            long decimal = Long.parseLong(flippedStr, 2);
    
    
            return decimal;
    
        }