1. 程式人生 > >Code War每天一練第二天

Code War每天一練第二天

sent stddef pre binary convert sting array amp 每天

Given an array of one‘s and zero‘s convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11


將字符數組轉化成整數
res = x

n

+x

n-1

+x

n-2

.......x

1

+x0



#include <stddef.h>

unsigned binary_array_to_numbers(const unsigned *bits, size_t count) {
  unsigned res = 0;
  for (size_t i = 0; i < count; i++)
    res = res << 1 | bits[i];
  return res;
}

Code War每天一練第二天