实例二:取n的第k位

方法:a>> k & 1
某值a右移K位后与整数“1”进行与运算。即把需要第几位就右移几位。

例子:

        0000 1000 ------8
右移3位     0000 0001 ------1
与1进行与操作  0000 0001 ------1

结果:       0000 0001 ------1


代码:
int _tmain(int argc, _TCHAR* argv[])
{
  int nValue,k,nResult=0;
  cout << "请输入要进行处理的数字:";
  cin >> nValue;
  cout << endl << "请输入要进行取的第几位:";
  cin >> k;
  if (nValue != 1)
  {
    nResult = nValue >> k & 1;
    cout << "该位的值:" << nResult << endl;
  }
  else
  {  
    cout << "该位的值:1" <<endl;
  }
  system("pause");
  return 0;
};

相关文章:

  • 2021-06-13
  • 2021-09-27
  • 2022-12-23
  • 2021-07-18
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
猜你喜欢
  • 2021-12-28
  • 2021-07-05
  • 2021-11-18
  • 2022-01-23
  • 2021-06-30
  • 2022-12-23
相关资源
相似解决方案