Round to next greater multiple of 8
Given an unsigned integer x. Round it up to the next greater multiple of 8 using bitwise operations only.
Input : 35 Output : 40 Input : 64 Output : 64 (As 64 is already a multiple of 8. So, no modification is done.)
Solution 1: We first add 7 and get a number x + 7, then we use the technique to find next smaller multiple of 8 for (x+7). For example, if x = 12, we add 7 to get 19. Now we find next smaller multiple of 19, which is 16.
Solution 2: An efficient approach to solve this problem using bitwise AND operation is:
x = (x + 7) &(-8)
This will round up x to the next greater multiple of 8.
Time Complexity: O(1)
Space Complexity: 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.