Swapping string case using a binary number in JavaScript

We need to write a JavaScript function that takes a string and a number, then uses the binary representation of the number to determine which alphabetic characters should have their case swapped.

Problem

Each bit in the binary representation of the number specifies whether to swap the case for each alphabetic character:

  • If the bit is 1, swap the case (lowercase ? uppercase, uppercase ? lowercase)
  • If the bit is 0, leave the character as is
  • When we reach the end of the binary representation, start again from the first bit
  • Non-alphabetic characters remain unchanged

How It Works

The algorithm works in several steps:

  1. Convert the number to binary representation
  2. Count alphabetic characters in the string
  3. Extend the binary string by repeating it until it covers all alphabetic characters
  4. For each character, check if it's alphabetic and if the corresponding bit is 1
  5. Swap case if both conditions are true

Example

Let's see how this works with a string and number:

const str = 'hey there';
const num = 21;

const swapCase = (str = '', num = 1) => {
    // Count alphabetic characters
    const alphaLength = str
        .split('')
        .reduce((acc, val) => val.toLowerCase() !== val.toUpperCase() ? ++acc : acc, 0);
    
    // Convert number to binary
    let binary = num.toString(2);
    
    // Extend binary string to cover all alphabetic characters
    while(binary.length < alphaLength) {
        binary += binary;
    }
    
    let res = '';
    let binaryIndex = 0;
    
    for(let i = 0; i < str.length; i++) {
        const el = str[i];
        
        // Check if character is alphabetic
        if(el.toUpperCase() !== el.toLowerCase()) {
            // Check if corresponding binary bit is 1
            if(+binary[binaryIndex] === 1) {
                if(el.toLowerCase() === el) {
                    res += el.toUpperCase();
                } else {
                    res += el.toLowerCase();
                }
            } else {
                res += el;
            }
            binaryIndex++;
        } else {
            res += el; // Non-alphabetic character
        }
    }
    
    return res;
};

console.log(`Original: "${str}"`);
console.log(`Number: ${num} (binary: ${num.toString(2)})`);
console.log(`Result: "${swapCase(str, num)}"`);
Original: "hey there"
Number: 21 (binary: 10101)
Result: "HeY TheRe"

Step-by-Step Breakdown

For the example above:

  1. String: "hey there" has 8 alphabetic characters
  2. Number 21 in binary: "10101" (5 bits)
  3. Extended binary: "10101101" (repeated to cover 8 characters)
  4. Apply bits to alphabetic characters: h(1)?H, e(0)?e, y(1)?Y, t(0)?t, h(1)?H, e(0)?e, r(1)?R, e(0)?e
  5. Result: "HeY TheRe"

Key Points

  • Only alphabetic characters are affected by the binary bits
  • Spaces and other non-alphabetic characters remain unchanged
  • The binary pattern repeats when there are more alphabetic characters than bits
  • The function handles both uppercase and lowercase characters correctly

Conclusion

This function demonstrates how binary representations can control string transformations. It's useful for creating patterns in text processing and showcases bitwise operations in practical scenarios.

Updated on: 2026-03-15T23:19:00+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements