资讯专栏INFORMATION COLUMN

[LintCode] Swap Bits

ls0609 / 3215人阅读

Problem

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Example

5 = (101)2 => (1010)2 = 10

Solution
public class Solution {
    /*
     * @param x: An integer
     * @return: An integer
     */
    public int swapOddEvenBits(int x) {
        //keep all odd "1"
        int odd = x & 0x55555555;
        //keep all even "1"
        int even = x & 0xaaaaaaaa;
        //shift odd "1"s left
        odd <<= 1;
        //shift even "1"s right (unsigned)
        even >>>= 1;
        return odd + even;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68191.html

相关文章

  • [LintCode/CC] Update Bits [Merge Bits]

    Problem Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at...

    KnewOne 评论0 收藏0
  • [LintCode] Flip Bits

    摘要:的二进制补码就是个,因此这道题一定要考虑正负号的问题。然后去检查的二进制包含多少个,方法是对的每一位除以取余。如果为,就说明那一位为,即和在那一位不同,需要进行转换。每次取余之后,减小为二分之一,删除已经检查过的高位。 Problem Determine the number of bits required to flip if you want to convert integer...

    joyvw 评论0 收藏0
  • [LintCode] UTF-8 Validation

    Problem A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code.For n-bytes character, the first n...

    tolerious 评论0 收藏0
  • [LintCode] Swap Two Nodes in Linked List

    摘要:建立结点,指向可能要对进行操作。找到值为和的结点设为,的前结点若和其中之一为,则和其中之一也一定为,返回头结点即可。正式建立,,以及对应的结点,,然后先分析和是相邻结点的两种情况是的前结点,或是的前结点再分析非相邻结点的一般情况。 Problem Given a linked list and two values v1 and v2. Swap the two nodes in th...

    wua_wua2012 评论0 收藏0
  • [LintCode] Swap Nodes in Pairs

    摘要:指针为,我们选择的两个结点是和。要注意循环的边界条件,这两个结点不能为空。主要思路是先用和两个新结点去保存和两个结点。完成交换之后,连接和,并让前进至此时的结点。 Problem Given a linked list, swap every two adjacent nodes and return its head. Example Given 1->2->3->4, you sh...

    EscapedDog 评论0 收藏0

发表评论

0条评论

ls0609

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<