当前位置: 首页>>代码示例>>用法及示例精选>>正文


Java Java lang.Long.builtcount()用法及代码示例


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()函数:

程序1:

// 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")); 


相关用法

注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Java lang.Long.builtcount() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。