zoukankan      html  css  js  c++  java
  • 将一个4字节整数的二进制表示中的001替换为011

    题目:将一个4字节整数的二进制表示中的001替换为011

    答:

    int replace(int num)
    {
        unsigned int mode3bit = 7;
        unsigned int mode1bit = 1;
        int shift = 0;
        int result = 0;
        while (shift < 32)
        {
            while (shift < 32 && (num & (mode3bit<<shift)) != (1<<shift))
            {
                result += (num & (mode1bit<<shift));
                shift++;
            }
            if (shift >= 32)
            {
                break;
            }
            else if (32 - shift < 3)  //高位不足3位
            {
                result += (num & (mode3bit<<shift));
                break;
            }
            result += (3<<shift);
            shift += 3;
            
        }
        return result;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int num = 12345678;                        //0b0000 0000 1011 1100 0110 0001 0100 1110
        assert(29156190 == replace(num)); //29156190 0b0000 0001 1011 1100 1110 0011 0101 1110
    
        num = 1227133513;                              //0b0100 1001 0010 0100 1001 0010 0100 1001
        assert(1533916891 == replace(num)); //1533916891 0b0101 1011 0110 1101 1011 0110 1101 1011
    
        num = 613566757;                               //0b0010 0100 1001 0010 0100 1001 0010 0101
        assert(1840700269 == replace(num)); //1840700269 0b0110 1101 1011 0110 1101 1011 0110 1101
    
        num = -809737911;                              //0b1100 1111 1011 1100 0110 0001 0100 1001
        assert(-541269157 == replace(num)); //-541269157 0b1101 1111 1011 1100 1110 0011 0101 1011
    
        num = -920350135;                                //0b1100 1001 0010 0100 1001 0010 0100 1001
        assert(-613566757 == replace(num)); //-613566757 //0b1101 1011 0110 1101 1011 0110 1101 1011
    
        return 0;
    }
  • 相关阅读:
    HDU
    POJ
    POJ
    POJ
    POJ
    POJ
    POJ
    SPFA算法——最短路径
    POJ1251 Jungle Roads Kruskal+scanf输入小技巧
    MongoDB--关于数据库及选择MongoDB的原因
  • 原文地址:https://www.cnblogs.com/venow/p/2868085.html
Copyright © 2011-2022 走看看