Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
binary
communitycreator
trailingzeros
integer

What is Integer.numberOfTrailingZeros() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The numberOfTrailingZeros() method of the Integer class is a static method that we can use to get the total number of zero bits. These zero bits follow the lowest-orderrightmost one-bit in the two’s complement binary form of the provided integer value.

This method returns 32 if there are no one-bits in the binary representation of the integer value.

Syntax

public static int numberOfTrailingZeros(int i)

Parameters

int i: The integer value whose number of trailing zeros is to be computed.

Return value

numberOfTrailingZeros() returns the number of trailing zeros in the 32-bit representation of the integer.

Examples

Let’s understand this method with the help of a few examples.

Example 1

  • int value: 123
  • Binary representation of 123: 1111011

The lowest one-bit of 123 in its binary representation is the rightmost one-bit.

The number of trailing zeros for 123 is 0.

Example 2

  • int value: 12
  • Binary representation of 12: 1100

The lowest one-bit of 12 in its binary representation is at position 2.

The number of trailing zeros for 12 is 2.

Code

public class Main{
private static void numberOfTrailingZeros(int number){
System.out.println("Binary Representation of " + number + " - " + Integer.toBinaryString(number));
System.out.println("Number of Trailing Zeros of " + number + " - "+ Integer.numberOfTrailingZeros(number));
}
public static void main(String[] args){
numberOfTrailingZeros(123);
System.out.println("----------");
numberOfTrailingZeros(0);
System.out.println("----------");
numberOfTrailingZeros(12);
}
}

RELATED TAGS

java
binary
communitycreator
trailingzeros
integer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring