ProDeveloperTutorial.com

教程和国彩网解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统国彩网
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

计算一个数字的平方,并使用按位运算符检查该数字是偶数还是奇数。

前开发者教程 2019年2月18日

使用按位运算符计算数字的平方。

二进制乘法的真值表如下:
0 x 0 = 00 x 1 = 01 x 0 = 01 x 1 = 1

在看编码部分之前,让我们执行4和3的二进制乘法。

4二进制是100
3二进制是011

步骤如下:

可以使用按位运算符执行以上步骤。

使用按位运算符检查数字是偶数还是奇数。

要对此进行检查,我们需要查看最右边的位。如果最右边的位为1,则其他为奇数,为偶数。

因此,为了实现这一点,我们使用(num&1),会给我们结果。

例:

例:
For 9:

      9 ->        1 0 0 1
      1 ->     &  0 0 0 1
      -------------------
      result->    0 0 0 1

For 14:

       14 ->      1 1 1 0
       1  ->   &  0 0 0 1
       ------------------
       result->   0 0 0 0

C ++解决方案

#include<iostream>
#include<vector>
#include<string>

using namespace std;

void check_even_odd(int num)
{

	if(num & 1)
		cout<<"The number "<< num<<" is odd"<<endl;
	else
		cout<<"The number "<<num<<" is even"<<endl;
}

void get_square(int num)
{
	int temp = num;
	int square = 0;
	int count = 0;

	while(temp > 0)
	{
	    if((temp & 1) == 1)
	    {
	        square += num << count;
	    }

	    temp = temp >> 1;
	    count++;
	}

	cout<<"The square of the number "<<num<<" is = "<<square<<endl;
}

int main()
{
	int num = 20;
	check_even_odd(num);
	get_square(num);

	return 0;
}


输出:

The number 20 is even

The square of the number 20 is = 400

 

该网站上可用的教程列表:

C国彩网20+章C ++国彩网80+章
100多个编码问题数据结构和算法85+章
系统设计20+章Shell脚本编写12章
4g LTE 60+章节最常见的编码问题
5G NR 50+章Linux系统国彩网20+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性国彩网问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和国彩网解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的
    <dd id="GXyIH0i"></dd>
    1. <xmp id="cVbchWw">
      <strong id="HU9ITbT"></strong>
      <address id="RMwriVB" class="Rwyhcdy"></address>




    2. <ol id="gvSIfME"></ol>
    3. <abbr class="LdQhnDE"><cite id="UEPWYLp"></cite></abbr>

          <option class="a5ZSvUm"><figure id="vYygnNa" class="vAsaEzP"><audio id="li9Kp37"></audio></figure></option>

          <param id="Xp4U8Kb"><applet id="l9K2OQB"></applet></param>


        1. <hgroup id="teTLaPf" class="te4dR6a"><dt id="obR1IUE"><label id="klgHXRr" class="k9S0Thc"><samp id="RGjX1aZ"></samp></label></dt></hgroup>
        2. <select id="ZzPwnqF" class="Zk98Nn2"></select>