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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 2953·2021-09-26 10:18
閱讀 5281·2021-09-22 15:02
閱讀 2796·2019-08-30 15:53
閱讀 1841·2019-08-29 18:41
閱讀 2692·2019-08-27 10:58
閱讀 2623·2019-08-26 13:49
閱讀 2750·2019-08-26 12:17
閱讀 901·2019-08-26 11:49