给定一个无符号整数x。仅使用按位运算将其四舍五入为下一个更大的8的倍数。
例子:
Input : 35
Output : 40
Input : 64
Output : 64 (As 64 is already a multiple of 8. So, no modification is done.)
解决方案1:我们首先加7并得到一个数字x + 7,然后使用该技术为(x + 7)找到下一个较小的8的倍数。例如,如果x = 12,我们将7加到19。现在我们找到19的下一个较小倍数,即16。
解决方案2:使用按位与运算解决此问题的有效方法是:
x =(x + 7)&(-8)
这会将x舍入为8的下一个更大的倍数。
C++
// CPP program to find smallest greater multiple
// of 8 for a given number
#include
using namespace std;
// Returns next greater multiple of 8
int RoundUp(int& x)
{
return ((x + 7) & (-8));
}
int main()
{
int x = 39;
cout << RoundUp(x);
return 0;
}
Java
// Java program to find smallest
// greater multiple of 8 for
// a given number
import java.util.*;
import java.lang.*;
// Returns next greater
// multiple of 8
class GFG
{
static int RoundUp(int x)
{
return ((x + 7) & (-8));
}
// Driver Code
public static void main(String args[])
{
int x = 39;
System.out.println(RoundUp(x));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Python 3
# Python 3 program to find
# smallest greater multiple
# of 8 for a given number
# Returns next greater
# multiple of 8
def RoundUp(x):
return ((x + 7) & (-8))
# Driver Code
x = 39
print(RoundUp(x))
# This code is contributed
# by prerna saini
C#
// C# program to find smallest
// greater multiple of 8 for
// a given number
using System;
// Returns next greater
// multiple of 8
class GFG
{
static int RoundUp(int x)
{
return ((x + 7) & (-8));
}
// Driver Code
public static void Main()
{
int x = 39;
Console.WriteLine(RoundUp(x));
}
}
// This code is contributed
// by SoumikMondal
PHP
输出:
40
时间复杂度: O(1)
空间复杂度: O(1)