Coding Exercise - Flip the Integers (Bit Manipulation) - 编程练习题:翻转整数位

in #programming8 years ago (edited)

Question: Write a function to compute the number of bits required to convert a integer to another.
For example, Input 29 (or 11101), 15 (or 01111) the output is 2.

It may seem complex but it is actually easy to do. The number of different bits can be counted by the exclusive OR (XOR). If the XOR of two bits are 1, which means a flip is required. In the following, we just shift the result of A xor B and count each bit if it is one:

int bitSwapRequired(int a, int b) {
  int count = 0;
  for (int c = a^b; c != 0; c >>>= 1) {
    count += c & 1;
  }
  return count;
}

However, this can be improved a little bit better. Instead of shifting one bit at a time, we can use X & (X - 1) to clear the least significant bit.

int bitSwapRequired(int a, int b) {
  int count = 0;
  for (int c = a^b; c != 0; c &= (c - 1)) {
    count ++;
  }
  return count;
}

This Bit Manipulation question is often asked in a interview, so it is worth remembering the tricks!

Reposted to my blog

Support me and my work as a witness - witness thread by

  1. voting me here, or
  2. voting me as a proxy.

Thank you! Some of My Contributions: SteemIt Tutorials, Robots, Tools and APIs


题意:给定两个整数,计算从一个整数需要翻转几个位才能到另一个整数。
比如:给定29 二进制为11101 和 15,二进制是01111,则答案是2次。

这题的关键就是用 XOR 异或来获得两个整数不同位。因为只有当两个位不一样的时候 异或的结果才是1。所以我们可以写成以下循环,每次向右移1位,累计 c & 1

int bitSwapRequired(int a, int b) {
  int count = 0;
  for (int c = a^b; c != 0; c >>>= 1) {
    count += c & 1;
  }
  return count;
}

我们还可以稍微改进一下,就是用 x & (x - 1) 来移除最右边的那个1。这样循环可以写成:

int bitSwapRequired(int a, int b) {
  int count = 0;
  for (int c = a^b; c != 0; c &= (c - 1)) {
    count ++;
  }
  return count;
}

这题还是在初面的时候挺常见的,也是较简单,但是如果没有看过当场还不一定想出一个很好的方法。

刚刚同步到我的博客

支持我的工作 支持我成为 见证人

  1. 请在 这里 投我一票, 或者
  2. 设置我 为代理.

谢谢您! 我的贡献:SteemIt 工具、API接口、机器人和教程

股东工具

  1. 成为股东:代理5 SP 即可 (退出股东 输入 0即可)
  2. 查询当前股东

请注意:每次代理都是以最后一次输入的SP数量为标准,比如已经代理10 SP,想多代理5 SP则需要输入 最后的数字 15 SP(而不是 5!)

Sort:  

学习编程,要从娃娃抓起

专门写了篇13看看51sp的效果,貌似autoupvote罢工了😂

Posted using Partiko iOS

我看了一下,你写的这篇时间还算在 23号,上一次点赞是23号(23小时前),因为一天就一篇……

原来是这样看的😅

一会你再写一篇试试?😅

貌似足球队已到场🤓

哦哦,那可能是数据延时更新了。

再说,胡扯也是有节操的,不能滥扯🤣

专门写了篇13看看51sp的效果,貌似autoupvote罢工啦~

Posted using Partiko iOS

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.083
BTC 61221.02
ETH 1642.72
USDT 1.00
SBD 0.42