国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode] Flip Bits

joyvw / 1010人閱讀

摘要:的二進(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.

Example

Given 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)檢查過的高位。

Solution
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

相關(guān)文章

  • [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 評(píng)論0 收藏0
  • [LintCode] Swap Bits

    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 => ...

    ls0609 評(píng)論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 評(píng)論0 收藏0
  • [LintCode] Count 1 in Binary [典型位運(yù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...

    ZHAO_ 評(píng)論0 收藏0
  • [LintCode] Gray Code

    摘要:參考了的算法,簡(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...

    cocopeak 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<