Find the K-th Character in String Game I

easy bit manipulation math recursion

Problem

Start with word = "a". One operation makes a copy of word with every letter shifted to the next letter of the alphabet, then appends that copy to the end. So "a""ab""abbc""abbcbccd", the length doubling each time. Given a positive integer k, return the k-th character (1-indexed) once word has at least k characters.

Inputk = 5
Output"b"
After three operations word = "abbcbccd"; the 5th character is "b". Equivalently, k−1 = 4 = binary 100, which has one set bit, so the answer is 'a' + 1 = 'b'.

def kthCharacter(k):
    # The k-th char (1-indexed) is decided by position k-1.
    # Each "1" bit of k-1 means one alphabet shift was applied,
    # so the answer is 'a' shifted by popcount(k - 1).
    shifts = bin(k - 1).count("1")
    return chr(ord("a") + shifts)
function kthCharacter(k) {
  // Look at the 0-indexed position p = k - 1.
  // Count its set bits: each one is one alphabet shift.
  let p = k - 1, shifts = 0;
  while (p > 0) { shifts += p & 1; p >>= 1; }
  return String.fromCharCode(97 + shifts);
}
char kthCharacter(int k) {
    // Position p = k - 1; popcount(p) = number of shifts.
    int p = k - 1, shifts = 0;
    while (p > 0) { shifts += p & 1; p >>= 1; }
    return (char) ('a' + shifts);
}
char kthCharacter(int k) {
    // popcount of (k - 1) tells how many +1 shifts apply.
    int p = k - 1, shifts = 0;
    while (p > 0) { shifts += p & 1; p >>= 1; }
    return (char) ('a' + shifts);
}
Time: O(log k) Space: O(1)