📜  Javalang.Long.builtcount()方法在Java中与实施例

📅  最后修改于: 2022-05-13 01:57:13.175000             🧑  作者: Mango

Javalang.Long.builtcount()方法在Java中与实施例


Java .lang.Long.bitCount()是Java中的一个内置函数,它以数字的二进制表示形式返回设置位的数量。它接受一个单一的强制性参数编号,其设置位的数量被返回。

句法:

public static long bitCount(long num)
Parameters:
num - the number passed 
Returns:
the number of set bits in the binary representation of the number 

例子:

Input : 8 
Output : 1
Explanation: Binary representation : 1000 
No of set bits=1 

Input : 1032
Output : 2
Explanation: binary representation = 10000001000
no of set bits = 2

下面的程序说明了Java.lang.Long.bitCount()函数:

方案一:



// Java program that demonstrates the use of
// Long.bitCount() function
  
// include lang package
import java.lang.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        long l = 1032;
  
        // prints the binary representation of the number
        System.out.println("binary representation = " + Long.toBinaryString(l));
  
        // prints the number of set bits
        System.out.println("no of set bits = " + Long.bitCount(l));
    }
}

输出:

binary representation = 10000001000
no of set bits = 2

程序 2:当参数中传递负数时

// Java program that demonstrates the use of
// Long.bitCount() function
// Negative number
  
// include lang package
import java.lang.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        long l = -1032;
  
        // prints the binary representation of the number
        System.out.println("binary representation = " + Long.toBinaryString(l));
  
        // prints the number of set bits
        System.out.println("no of set bits = " + Long.bitCount(l));
    }
}

输出:

binary representation = 1111111111111111111111111111111111111111111111111111101111111000
no of set bits = 60 

错误:如果将 long 以外的任何数据类型作为参数传递,该函数将返回错误。

程序 3:当十进制数作为参数传递时

// Java program that demonstrates the use of
// Long.bitCount() function
// decimal number
  
// include lang package
import java.lang.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // prints the number of set bits
        System.out.println("no of set bits = " + Long.bitCount(11.23));
    }
}

输出:

prog.java:15: error: incompatible types: possible lossy conversion from double to long
        System.out.println("no of set bits = " + Long.bitCount(11.23));

程序 4:当字符串编号作为参数传递时

// Java program that demonstrates the use of
// Long.bitCount() function
// string number
  
// include lang package
import java.lang.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // prints the number of set bits
        System.out.println("no of set bits = " + Long.bitCount("12"));
    }
}

输出:

prog.java:15: error: incompatible types: String cannot be converted to long
        System.out.println("no of set bits = " + Long.bitCount("12"));