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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.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...
摘要:的二進(jìn)制補(bǔ)碼就是個(gè),因此這道題一定要考慮正負(fù)號(hào)的問題。然后去檢查的二進(jìn)制包含多少個(gè),方法是對(duì)的每一位除以取余。如果為,就說明那一位為,即和在那一位不同,需要進(jìn)行轉(zhuǎn)換。每次取余之后,減小為二分之一,刪除已經(jīng)檢查過的高位。 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...
摘要:建立結(jié)點(diǎn),指向可能要對(duì)進(jìn)行操作。找到值為和的結(jié)點(diǎn)設(shè)為,的前結(jié)點(diǎn)若和其中之一為,則和其中之一也一定為,返回頭結(jié)點(diǎn)即可。正式建立,,以及對(duì)應(yīng)的結(jié)點(diǎn),,然后先分析和是相鄰結(jié)點(diǎn)的兩種情況是的前結(jié)點(diǎn),或是的前結(jié)點(diǎn)再分析非相鄰結(jié)點(diǎn)的一般情況。 Problem Given a linked list and two values v1 and v2. Swap the two nodes in th...
摘要:指針為,我們選擇的兩個(gè)結(jié)點(diǎn)是和。要注意循環(huán)的邊界條件,這兩個(gè)結(jié)點(diǎn)不能為空。主要思路是先用和兩個(gè)新結(jié)點(diǎn)去保存和兩個(gè)結(jié)點(diǎn)。完成交換之后,連接和,并讓前進(jìn)至此時(shí)的結(jié)點(diǎn)。 Problem Given a linked list, swap every two adjacent nodes and return its head. Example Given 1->2->3->4, you sh...
閱讀 3165·2021-09-26 10:18
閱讀 5416·2021-09-22 15:02
閱讀 2863·2019-08-30 15:53
閱讀 1911·2019-08-29 18:41
閱讀 2768·2019-08-27 10:58
閱讀 2690·2019-08-26 13:49
閱讀 2818·2019-08-26 12:17
閱讀 965·2019-08-26 11:49