运算符面试题(剑指offer,面试宝典,牛客网)
生活随笔
收集整理的這篇文章主要介紹了
运算符面试题(剑指offer,面试宝典,牛客网)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 利用一個宏實現兩個數的交換?
- 不使用if,?,switch或者其他判斷語句比較兩個變量的大小?
- 利用位運算實現加法?
- 以下程序輸出結果是?
- 用位運算實現求平均數?
- 不用循環判斷一個數是不是2的N次方?
利用一個宏實現兩個數的交換?
#include <iostream> using namespace std;#define SWAP(a, b) {char tempbuf[10]; memcpy(tempbuf, &a, sizeof(a)); memcpy(&a, &b, sizeof(b)); memcpy(&b, tempbuf, sizeof(b)); }int main() {int a = 2;int b = 10;SWAP(a, b);cout<<a<<endl;cout<<b<<endl;return 0; }不使用if,?,switch或者其他判斷語句比較兩個變量的大小?
#include <iostream> using namespace std;bool fun(int a, int b) {return a > b; }int max(int a, int b) {bool flag = fun(a, b);return flag * a + (1 - flag) * b;//巧妙 }int main() {return 0; } #include <iostream> using namespace std;int max(int a, int b) {return ((a + b) + abs(a - b)) / 2; }int main() {int a = 2;int b = 5;int n = max(a, b);cout<<n<<endl;return 0; }利用位運算實現加法?
#include <iostream> using namespace std;int Add(int a, int b) {if(b == 0){return a;}int sum, carry;sum = a ^ b;carry = (a & b) << 1;return Add(sum, carry); }int main() {int a = 10;int b = 245;cout<<Add(a, b)<<endl;return 0; }以下程序輸出結果是?
#include <iostream> using namespace std;int main() {unsigned char a = 0xa5; //首先是1010 0101unsigned char b = ~a >> 4 + 1; //~優先級位于第2 >> 位于第6 +位于第5 所以先取反,然后計算出5,然后右移5位//a 取反 0101 1010 但是會發生整數提升,即a提升為int型,即左邊補24個0,這時再右移5位變成//左邊24個1 加上 0101 1010,由于char是一個字節,所以取8位變成 1111 1010 即250//cout<<b<<endl;printf("%d\n", b);return 0; }用位運算實現求平均數?
#include <iostream> using namespace std;int Average(int x, int y) {return (x & y) + ((x ^ y) >> 1); }int main() {int a = 10;int b = 30;cout<<Average(a, b)<<endl;return 0; }不用循環判斷一個數是不是2的N次方?
#include <iostream> using namespace std;int main() {unsigned int a = 0;cout<<"Please input a number:";cin>>a;if((a & (a - 1)) == 0){cout<<"yes"<<endl;}else{cout<<"no"<<endl;}return 0; }總結
以上是生活随笔為你收集整理的运算符面试题(剑指offer,面试宝典,牛客网)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS安装yum 镜像 举例阿里云
- 下一篇: C语言关键字 ISO/ANSI C90