當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。