title: Count Total Set Bits In All Numbers From 1 To N
signature: function countTotalSetBitsInAllNumbersFrom1ToN(n) {
test_code: 
  
  // SOLUTION CODE
  // ============================================
  PLACEHOLDER_CODE_BODY
  
  // TESTING CODE 
  // ============================================
  function convertToString(value) {
      return JSON.stringify(value, function (key, val) {
          if (val instanceof Set) {
              return Array.from(val);
          } return val;});
  }
  
  function validateSolution(actual, expected){
      return convertToString(actual)===convertToString(expected);
  }
  
  function driver(n, expected){
      try{
          if (validateSolution(PLACEHOLDER_FN_NAME(n),expected)){
              return "PASSED";
          }
          return "FAILED";
      } catch (error) {
        return error.name;
      }
      
  }
      
  function main(){
    let result = '';
    result = driver(90, 279);
    console.log(`TEST-0...${result}`);
  
    result = driver(56, 159);
    console.log(`TEST-1...${result}`);
  
    result = driver(43, 112);
    console.log(`TEST-2...${result}`);
  
    result = driver(31, 80);
    console.log(`TEST-3...${result}`);
  
    result = driver(77, 231);
    console.log(`TEST-4...${result}`);
  
    result = driver(35, 88);
    console.log(`TEST-5...${result}`);
  
    result = driver(43, 112);
    console.log(`TEST-6...${result}`);
  
    result = driver(66, 197);
    console.log(`TEST-7...${result}`);
  
    result = driver(15, 32);
    console.log(`TEST-8...${result}`);
  
    result = driver(95, 304);
    console.log(`TEST-9...${result}`);
  
    process.exit(0);
  };
  
  if (require.main === module) {
    main();
  }
source_py: def count_total_set_bits_in_all_numbers_from_1_to_n(n):
      i = 0
      ans = 0
      while ((1 << i) <= n):
          k = 0
          change = (1 << i)
          for j in range(0, (n + 1)):
              ans += k
              if (change == 1):
                  k = (not k)
                  change = (1 << i)
              else:
                  change -= 1
          i += 1
      return ans
source_cpp: int count_total_set_bits_in_all_numbers_from_1_to_n(int n) {
    int i = 0;
    int ans = 0;
    while ( ( 1 << i ) <= n ) {
      bool k = 0;
      int change = 1 << i;
      for ( int j = 0;
      j <= n;
      j ++ ) {
        ans += k;
        if ( change == 1 ) {
          k = ! k;
          change = 1 << i;
        }
        else {
          change --;
        }
      }
      i ++;
    }
    return ans;
  }