title: Count Total Set Bits In All Numbers From 1 To N
signature: func countTotalSetBitsInAllNumbersFrom1ToN(n int) int {
test_code: package main
  
  import (
      "fmt"
      "reflect"
      "math"
      "sort"
  )
  
  // SOLUTION CODE
  // ===================================
  PLACEHOLDER_CODE_BODY
  
  // TESTING CODE
  // ===================================
  func validateSolution(actual int, expected int) bool {
      return reflect.DeepEqual(actual,expected)
  }
  
  func driver(n int, expected int) string {
      if validateSolution(PLACEHOLDER_FN_NAME(n),expected) {
              return "PASSED"
      }
      return "FAILED"
  
  }
  
  func main() {
  
      // Use imports to avoid undefined errors
      var _ = reflect.DeepEqual
      _ = math.Abs
      _ = sort.Sort
      result := ""
      result = driver(90, 279)
      fmt.Printf("TEST-0...%s\n", result)
      
      result = driver(56, 159)
      fmt.Printf("TEST-1...%s\n", result)
      
      result = driver(43, 112)
      fmt.Printf("TEST-2...%s\n", result)
      
      result = driver(31, 80)
      fmt.Printf("TEST-3...%s\n", result)
      
      result = driver(77, 231)
      fmt.Printf("TEST-4...%s\n", result)
      
      result = driver(35, 88)
      fmt.Printf("TEST-5...%s\n", result)
      
      result = driver(43, 112)
      fmt.Printf("TEST-6...%s\n", result)
      
      result = driver(66, 197)
      fmt.Printf("TEST-7...%s\n", result)
      
      result = driver(15, 32)
      fmt.Printf("TEST-8...%s\n", result)
      
      result = driver(95, 304)
      fmt.Printf("TEST-9...%s\n", result)
      
          
  }
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;
  }