Reputation: 3371
I need to calculate the nearest bigger integer devisible by 8. For examples:
a=0
, the nearest bigger integer devisible by 8 is 0
.a=1
to a=7
, the nearest bigger integer devisible by 8 is 8
.a=8
, the nearest bigger integer devisible by 8 is 8
.a=x*8+1
to a=x*8+7
, the nearest bigger integer devisible by 8 is a=(x+1)*8
.a=x*8
, the nearest bigger integer devisible by 8 is a=x*8
itself.How should I implement this function int nearestBiggerIntegerDevisibleBy8(int a)
in C++ bitwise operation (fastest)?
Upvotes: 1
Views: 545
Reputation: 4288
This one way to go about it
#include <stdio.h>
int nearestBiggerInt(int n){
n += 7;
return (n & ~7);
}
int main()
{
for (int i = 0; i < 20; i++)
printf("%d -> %d\n", i, nearestBiggerInt(i));
return 0;
}
Output
0 -> 0
1 -> 8
2 -> 8
3 -> 8
4 -> 8
5 -> 8
6 -> 8
7 -> 8
8 -> 8
9 -> 16
10 -> 16
11 -> 16
12 -> 16
13 -> 16
14 -> 16
15 -> 16
16 -> 16
17 -> 24
18 -> 24
19 -> 24
Upvotes: 8