给定一个无符号整数x。仅使用按位运算将其四舍五入为下一个较小的8的倍数。
例子:
Input : 35
Output : 32
Input : 40
Output : 40
As 40 is already a multiple of 8. So, no
modification is done.
解决方案1:使用算术运算运算符解决此问题的简单方法是:
令x为数字,
x = x –(x%8)
这会将x舍入为8的下一个较小倍数。但是我们不允许使用算术运算运算符。
解决方案2:使用按位与运算解决此问题的有效方法是:x = x&(-8)
这会将x舍入为8的下一个较小倍数。该想法基于以下事实:8的倍数中的最后三个位必须为0,
下面是上述想法的实现:
C++
// CPP program to find next smaller
// multiple of 8.
#include
using namespace std;
int RoundDown(int& a)
{
return a & (-8);
}
int main()
{
int x = 39;
cout << RoundDown(x);
return 0;
}
Java
//Java program to find next smaller
// multiple of 8.
import java.io.*;
class GFG {
static int RoundDown(int a)
{
return a & (-8);
}
public static void main (String[] args) {
int x = 39;
System.out.println (RoundDown(x));
}
}
//This Code is Contributed by ajit
Python3
# Python 3 program to find next
# smaller multiple of 8.
def RoundDown(a):
return a & (-8)
# Driver Code
if __name__ == '__main__':
x = 39
print(RoundDown(x))
# This code is contributed
# by Surendra_Gangwar
C#
// C# program to find next smaller
// multiple of 8.
using System;
class GFG
{
static int RoundDown(int a)
{
return a & (-8);
}
public static void Main()
{
int x = 39;
Console.Write(RoundDown(x));
}
}
// This code is contributed
// by Akanksha Rai
PHP
输出:
32
时间复杂度:此方法的时间复杂度为O(1)
空间复杂度:此方法的空间复杂度为O(1)