This article was found from Geeksforgeeks.org.

Click here to see the original article.

Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y. 
For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers).

Examples:

Input: arr[] = {1, 2}
Output: 4
All pairs in array are (1, 1), (1, 2)
(2, 1), (2, 2)
Sum of bit differences = 0 + 2 +
2 + 0
= 4 Input: arr[] = {1, 3, 5}
Output: 8
All pairs in array are (1, 1), (1, 3), (1, 5)
(3, 1), (3, 3) (3, 5),
(5, 1), (5, 3), (5, 5)
Sum of bit differences = 0 + 1 + 1 +
1 + 0 + 2 +
1 + 2 + 0
= 8

Source: Google Interview Question

We strongly recommend you to minimize your browser and try this yourself first.

Simple Solution is to run two loops to consider all pairs one by one. For every pair, count bit differences. Finally return sum of counts. Time complexity of this solution is O(n2).

An Efficient Solution can solve this problem in O(n) time using the fact that all numbers are represented using 32 bits (or some fixed number of bits). The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set. Let this count be ‘count’. There would be “n-count” numbers with i’th bit not set. So count of differences at i’th bit would be “count * (n-count) * 2″.

Below is C++ implementation of above idea.

 // C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std; int sumBitDifferences(int arr[], int n)
{
int ans = ; // Initialize result // traverse over all bits
for (int i = ; i < ; i++)
{
// count number of elements with i'th bit set
int count = ;
for (int j = ; j < n; j++)
if ( (arr[j] & ( << i)) )
count++; // Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * );
} return ans;
} // Driver prorgram
int main()
{
int arr[] = {, , };
int n = sizeof arr / sizeof arr[];
cout << sumBitDifferences(arr, n) << endl;
return ;
}

最新文章

  1. smarty使用
  2. 番外一:关于thinkphp框架下的文件导入路径问题
  3. 多个精美的导航样式web2.0源码
  4. 【转】FPGA内部小数计算
  5. (IOS)BaiduFM 程序分析
  6. GridView实现一个图片加多个文本框
  7. Javascript 笔记与总结(2-10)删除节点,创建节点
  8. MongoDB (六) MongoDB 集合操作
  9. HDU1001
  10. 体验Lua
  11. MVC WEB api 自动生成文档
  12. 进一步解 apt-get 的几个命令
  13. MySQL与MongoDB之SQL语法对比
  14. C#保留2位小数的做法
  15. 如何访问IPV6?很简单,几个命令行即可。
  16. VMware虚拟机克隆Linux(CentOS)系统后找不到eth0网卡的问题(图文详解)
  17. 【IT笔试面试题整理】连续子数组的最大和
  18. POJ 2349 Arctic Network(最小生成树中第s大的边)
  19. 学习git踩坑之路
  20. 微信 小程序组件 加入购物车全套 one wxss

热门文章

  1. 社区版pycharm安装Django框架
  2. HDU 3954 Level up (线段树特殊懒惰标记)
  3. nagios原理及配置详解
  4. Scala 基础(4)—— 类和对象
  5. vue.$refs 的用法
  6. 【bzoj2079】[Poi2010]Guilds 构造结论题
  7. Spring Boot Executable jar/war 原理
  8. 2017 多校4 Wavel Sequence
  9. git上导出的maven项目转成正常的Dynamic web project
  10. gvim设置使用