使用按位运算符计算数字的平方。
二进制乘法的真值表如下:
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+章 |