zoukankan      html  css  js  c++  java
  • 剑指offer--3

    前言:继续学习剑指offer!!!

    面试题10:  

    这道题相对简单,但要对位运算了解。

    位运算大体上只有5种运算,总结如下:

    • 按位与 “&”:

    将参与运算的两操作数各对应的二进制位进行与

    操作,只有对应的两个二进位均为1时,结果的对

    应二进制位才为1,否则为0。

            通常用来将某变量中的某些位清0且同时保留其他位不变。
    也可以用来获取某变量中的某一位。
    例如,如果需要将int型变量n的低8位全置成0,而其余位
    不变,则可以执行:

            n = n & 0xffffff00;

    • 按位或“|”:

    按位或运算通常用来将某变量中的某些位置1且保
    留其他位不变。
    例如,如果需要将int型变量n的低8位全置成1,而
    其余位不变,则可以执行:
    n |= 0xff;
    0xff: 1111 1111

    • 按位异或 “^”
      按位异或运算通常用来将某变量中的某些位取反,
      且保留其他位不变。
      例如,如果需要将int型变量n的低8位取反,而其
      余位不变,则可以执行:
      n ^= 0xff;
      0xff: 1111 1111
    • 左移操作符<<

    实际上,左移1位,就等于是乘以2, 左移n位,就等于
    是乘以2n。而左移操作比乘法操作快得多。

    例如:
    9 << 4 相当于9乘16

    结果:144

    • 右移操作符 >>

    实际上, 右移n位,就相当于左操作数除以2n,并且将
    结果往小里取整。

    例如:

    -25 >> 4 = -2 -25除以16等于负1.几,往小里取整,-2更小
    -2 >> 4 = -1
    18 >> 4 = 1

    #include<stdio.h>
    
    int NumberOf1(int n)
    {
        int count=0;
        while(n)
        {   
            if(n&1)
                count++;
            n = n >>1;
        }   
        return count;
    }
    
    int main()
    {
        int n;
        puts("please input your number:");
        scanf("%d",&n);
        printf("numOf1:%d
    ",NumberOf1(n));
    
        return 0;
    }

    面试题11:

    注:比较简单,不写了。注意位运算比加减乘除快!!!

    面试题12:

    注:要考虑到n很大的情况.

    这个学习要先耽误一段时间,有新需求要做,而且还要交接员工离职留下的任务!!!

  • 相关阅读:
    Neko's loop HDU-6444(网络赛1007)
    Parameters
    SETLOCAL
    RD / RMDIR Command
    devenv 命令用法
    Cannot determine the location of the VS Common Tools folder.
    'DEVENV' is not recognized as an internal or external command,
    How to change Visual Studio default environment setting
    error signing assembly unknown error
    What is the Xcopy Command?:
  • 原文地址:https://www.cnblogs.com/liudw-0215/p/9167119.html
Copyright © 2011-2022 走看看