Round to next smaller multiple of 8
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:
Time Complexity: The time complexity of this approach is O(1)
Space Complexity: The space complexity of this approach is O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.