給定L和R兩個integer,找出L和R之間最大的A xor B,
當中A和B滿足 L<=A<=B<=R。
輸入:
兩行分別輸入L和R,
限制為1<=L<=R<=10的3次方。
輸出:
輸出如題所述的值。
解題:
基本上使用兩層的巢狀迴圈即可找出最大值,
唯獨要注意的是,
因為bitwise xor的符號"^"在編譯器的優先序會低於">"和"<",
故記得將其用括號包起來。
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
/*
* Complete the function below.
*/
int maxXor(int l, int r) {
int max = 0;
for(int a=l; a<=r; a++)
for(int b=a; b<=r; b++)
if((a^b) > max)
max = (a^b);
return max;
}
int main() {
int res;
int _l;
scanf("%d", &_l);
int _r;
scanf("%d", &_r);
res = maxXor(_l, _r);
printf("%d", res);
return 0;
}
沒有留言:
張貼留言