Given an unsigned integer x. Round it down to the next smaller multiple of 8 using bitwise operations only.
Input : 35 Output : 32 Input : 40 Output : 40 As 40 is already a multiple of 8. So, no modification is done.
Solution 1: A naive approach to solve this problem using arithmetic operators is :
Let x be the number then,
x = x – (x % 8)
This will round down x to the next smaller multiple of 8. But we are not allowed to use arithmetic operators.
Solution 2: An efficient approach to solve this problem using bitwise AND operation is: x = x & (-8)
This will round down x to the next smaller multiple of 8. The idea is based on the fact that last three bits in a multiple of 8 must be 0,
Below is the implementation of above idea:
# Python 3 program to find next
# smaller multiple of 8.
return a & (-8)
# Driver Code
if __name__ == ‘__main__’:
x = 39
# This code is contributed
# by Surendra_Gangwar
Time Complexity: The time complexity of this approach is O(1)
Space Complexity: The space complexity of this approach is O(1)
- Round to next greater multiple of 8
- Puzzle | 3 cuts to cut round cake into 8 equal pieces
- Immediate Smaller element in an N-ary Tree
- Count smaller values whose XOR with x is greater than x
- Previous smaller integer having one less number of set bits
- Largest number smaller than or equal to N divisible by K
- Count numbers (smaller than or equal to N) with given digit sum
- Count smaller numbers whose XOR with n produces greater value
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- Closest (or Next) smaller and greater numbers with same number of set bits
- Delete all the nodes from a doubly linked list that are smaller than a given value
- Efficiently check whether n is a multiple of 4 or not
- Find the largest multiple of 2, 3 and 5
- Find the multiple of x which is closest to a^b
- How to get multiple selected values of select box in php?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.