Given an unsigned integer x. Round it up to the next greater multiple of 8 using bitwise operations only.
Examples:
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.
C++
#include <bits/stdc++.h>
using namespace std;
int RoundUp( int & x)
{
return ((x + 7) & (-8));
}
int main()
{
int x = 39;
cout << RoundUp(x);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG
{
static int RoundUp( int x)
{
return ((x + 7 ) & (- 8 ));
}
public static void main(String args[])
{
int x = 39 ;
System.out.println(RoundUp(x));
}
}
|
Python 3
def RoundUp(x):
return ((x + 7 ) & ( - 8 ))
x = 39
print (RoundUp(x))
|
C#
using System;
class GFG
{
static int RoundUp( int x)
{
return ((x + 7) & (-8));
}
public static void Main()
{
int x = 39;
Console.WriteLine(RoundUp(x));
}
}
|
PHP
<?php
function RoundUp( $x )
{
return (( $x + 7) & (-8));
}
$x = 39;
echo RoundUp( $x );
?>
|
Javascript
<script>
function RoundUp(x)
{
return ((x + 7) & (-8));
}
let x = 39;
document.write(RoundUp(x));
</script>
|
Time Complexity: O(1)
Space Complexity: O(1)
An efficient approach to solve this problem is using shift operators, as the next greater multiple of 8 can be obtained as the product of 8 and (num + 7) / 8.
C++
#include <bits/stdc++.h>
using namespace std;
int RoundUp( int & x)
{
return ((x + 7) >> 3) << 3;
}
int main()
{
int x = 39;
cout << RoundUp(x);
return 0;
}
|
Java
import java.util.*;
class Main {
static int roundUp( int x)
{
return ((x + 7 ) >> 3 ) << 3 ;
}
public static void main(String[] args) {
int x = 39 ;
System.out.println(roundUp(x));
}
}
|
C#
using System;
class GFG {
static int RoundUp( int x)
{
return ((x + 7) >> 3) << 3;
}
public static void Main( string [] args)
{
int x = 39;
Console.WriteLine(RoundUp(x));
}
}
|
Javascript
function RoundUp(x)
{
return ((x + 7) >> 3) << 3;
}
let x = 39;
console.log(RoundUp(x));
|
Python3
def roundUp(x):
return ((x + 7 ) >> 3 ) << 3
x = 39
print (roundUp(x))
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Contact Us