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).
Example5 = (101)2 => (1010)2 = 10
Solutionpublic 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
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...
摘要:的二进制补码就是个,因此这道题一定要考虑正负号的问题。然后去检查的二进制包含多少个,方法是对的每一位除以取余。如果为,就说明那一位为,即和在那一位不同,需要进行转换。每次取余之后,减小为二分之一,删除已经检查过的高位。 Problem Determine the number of bits required to flip if you want to convert integer...
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...
摘要:建立结点,指向可能要对进行操作。找到值为和的结点设为,的前结点若和其中之一为,则和其中之一也一定为,返回头结点即可。正式建立,,以及对应的结点,,然后先分析和是相邻结点的两种情况是的前结点,或是的前结点再分析非相邻结点的一般情况。 Problem Given a linked list and two values v1 and v2. Swap the two nodes in th...
摘要:指针为,我们选择的两个结点是和。要注意循环的边界条件,这两个结点不能为空。主要思路是先用和两个新结点去保存和两个结点。完成交换之后,连接和,并让前进至此时的结点。 Problem Given a linked list, swap every two adjacent nodes and return its head. Example Given 1->2->3->4, you sh...
阅读 2883·2021-09-26 10:18
阅读 5128·2021-09-22 15:02
阅读 2746·2019-08-30 15:53
阅读 1820·2019-08-29 18:41
阅读 2670·2019-08-27 10:58
阅读 2606·2019-08-26 13:49
阅读 2725·2019-08-26 12:17
阅读 886·2019-08-26 11:49