Java Java () 方法与示例
Java.lang.Long.highestOneBit()是Java中的一个内置方法,它首先将数字转换为二进制,然后从左边开始查找第一个设置位,然后重置其余位,然后返回值。用简单的语言来说,如果一个数字的二进制表达式至少包含一个设置位,它返回 2^(从右 1 开始的最后一个设置位位置)。如果二进制表达式不包含任何设置位,则返回 0。
句法:
public static long highestOneBit(long num)
Parameters:
num - the number passed
Returns:
long value by only considering highest 1 bit in the argument.
例子:
Input : 9
Output : 8
Explanation: Binary Representation = 1001
It considers highest bit(at 4th from right) and now
reset rest of the bits i.e. 1000
so result = 1000 i.e. 8 or in simple terms, the last set
bit position from right is at position 4, hence 2^3=8
Input : 45
Output : 32
下面的程序说明了Java.lang.Long.highestOneBit()函数:
方案一:
// Java program that demonstrates the use of
// Long.highestOneBit() function
// include lang package
import java.lang.*;
public class GFG {
public static void main(String[] args)
{
long l = 9;
// returns a long value with at most a
// single one-bit, in the position
// of the highest-order ("rightmost")
// one-bit in the specified long value.
System.out.println("highest one bit = " + Long.highestOneBit(l));
l = 45;
System.out.println("highest one bit = " + Long.highestOneBit(l));
}
}
输出:
highest one bit = 8
highest one bit = 32
注意:负数的最高位在每种情况下都将始终相同,因此无论数字如何,每个负数的输出都是相同的。
程序2:下面的程序演示了传递负数时函数的使用。
// java program that demonstrates the use of
// Long.highestOneBit() function
// negative number
// include lang package
import java.lang.*;
public class GFG {
public static void main(String[] args)
{
long l = -15;
// prints the binary of a negative expression
System.out.println("Binary = " + Long.toBinaryString(l));
// returns a long value with at
// most a single one-bit, in the position
// of the highest-order ("rightmost")
// one-bit in the specified int value.
System.out.println("Highest one bit = " + Long.highestOneBit(l));
}
}
输出:
Binary = 1111111111111111111111111111111111111111111111111111111111110001
Highest one bit = -9223372036854775808
当十进制字符串值作为参数传递时,它会返回错误消息。
程序 3:在参数中传递十进制值时。
// java program that demonstrates the
// Long.highestOneBit() function
// decimal value in argument
// include lang package
import java.lang.*;
public class GFG {
public static void main(String[] args)
{
System.out.println("highest one bit = " + Long.highestOneBit(12.34));
}
}
输出:
prog.java:13: error: incompatible types: possible lossy conversion from double to long
System.out.println("highest one bit = " + Long.highestOneBit(12.34));
程序 3:在参数中传递字符串值时。
// java program that demonstrates the
// Long.highestOneBit() function
// string value in argument
// include lang package
import java.lang.*;
public class GFG {
public static void main(String[] args)
{
System.out.println("highest one bit = " + Long.highestOneBit("12"));
}
}
输出:
prog.java:13: error: incompatible types: String cannot be converted to long
System.out.println("highest one bit = " + Long.highestOneBit("12"));