码迷,mamicode.com
首页 > 其他好文 > 详细

Code War每天一练第二天

时间:2019-02-10 10:56:21      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:present   The   clu   class   which   ati   sign   int   for   

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每天一练第二天

标签:present   The   clu   class   which   ati   sign   int   for   

原文地址:https://www.cnblogs.com/zch-boke/p/10358661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!