摘要:的二進(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 n to integer m.
ExampleGiven n = 31 (11111), m = 14 (01110), return 2.
Note-1的二進(jìn)制補(bǔ)碼就是32個(gè)1,因此這道題一定要考慮正負(fù)號(hào)的問題。
先將a和b異或得到c,若c為負(fù),就說明a和b的符號(hào)不同,所以要多一次符號(hào)位的轉(zhuǎn)換。
然后去檢查c的二進(jìn)制包含多少個(gè)1,方法是對(duì)c的每一位除以2取余。如果為1,就說明那一位為1,即a和b在那一位不同,需要進(jìn)行轉(zhuǎn)換。每次取余之后,c減小為二分之一,刪除已經(jīng)檢查過的高位。
class Solution { public static int bitSwapRequired(int a, int b) { int c = a ^ b, count = 0; if (c < 0) { c ^= Integer.MIN_VALUE; count++; } while (c != 0) { count += c % 2; c /= 2; } return count; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65675.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 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 => ...
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...
摘要:這道題,給我解決了兩個(gè)疑問,還剩一個(gè)。首先是要用無(wú)符號(hào)右移運(yùn)算符,其次是可以用一個(gè)不斷左移的二進(jìn)制作為參照。 Problem Count how many 1 in binary representation of a 32-bit integer. Example Given 32, return 1 Given 5, return 2 Given 1023, return 9 Ch...
摘要:參考了的算法,簡(jiǎn)化了一下每個(gè)循環(huán)更新對(duì)應(yīng)最高位是第位,就增加個(gè)數(shù)為倒序循環(huán)次,會(huì)鏡像提取上一次循環(huán)產(chǎn)生的結(jié)果鏡像鏡像鏡像 Problem The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n r...
閱讀 3115·2023-04-25 15:02
閱讀 2806·2021-11-23 09:51
閱讀 2030·2021-09-27 13:47
閱讀 1984·2021-09-13 10:33
閱讀 957·2019-08-30 15:54
閱讀 2640·2019-08-30 15:53
閱讀 2853·2019-08-29 13:58
閱讀 881·2019-08-29 13:54