title: Count Total Set Bits In All Numbers From 1 To N
signature: count_total_set_bits_in_all_numbers_from_1_to_n <- function(n) {
test_code: 
  
  
  # SOLUTION CODE
  # ============================================
  PLACEHOLDER_CODE_BODY
  
  # TESTING CODE 
  # ============================================
  validate_solution <- function(actual, expected) {
      toString(actual)==toString(expected)
  }
  
  driver <- function(n, expected){
      if (validate_solution(PLACEHOLDER_FN_NAME(n), expected)){
          "PASSED"
      } else{
          "FAILED"
      }
  }
  
  main <- function() {
      cat(sprintf("TEST-0...%s\n",driver(
          90L, 
          279L
      )))
  
      cat(sprintf("TEST-1...%s\n",driver(
          56L, 
          159L
      )))
  
      cat(sprintf("TEST-2...%s\n",driver(
          43L, 
          112L
      )))
  
      cat(sprintf("TEST-3...%s\n",driver(
          31L, 
          80L
      )))
  
      cat(sprintf("TEST-4...%s\n",driver(
          77L, 
          231L
      )))
  
      cat(sprintf("TEST-5...%s\n",driver(
          35L, 
          88L
      )))
  
      cat(sprintf("TEST-6...%s\n",driver(
          43L, 
          112L
      )))
  
      cat(sprintf("TEST-7...%s\n",driver(
          66L, 
          197L
      )))
  
      cat(sprintf("TEST-8...%s\n",driver(
          15L, 
          32L
      )))
  
      cat(sprintf("TEST-9...%s\n",driver(
          95L, 
          304L
      )))
  
  }
  
  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;
  }