Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

how to find the highest power of 2 that divides a number?

/*
	This implementation shows how to easily
	find the highest power of 2 that divides
	a given number n.

	For example, if n=48 => answer = 16

	Time complexity: O(1)
	Space complexity: O(1)
*/

public class HighestPowerOf2 {
	private static int highestPowerOfTwo(int n) {
		return (n & (~(n - 1)));
	}

	public static void main(String[] args) {
		System.out.println(highestPowerOfTwo(48)); // 16
		System.out.println(highestPowerOfTwo(5)); // 1
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: spring @Bean destroyMethod 
Java :: get time stamp java 
Java :: how to convert outputstream to bytearrayoutputstream in java 
Java :: get boolean from string java 
Java :: how to use decimal format java 
Java :: into to string in java 
Java :: array to list 
Java :: read file in java 
Java :: java.lang.NoSuchMethodError: org.apache.logging.log4j.spi.LoggerContextFactory.isClassLoaderDependent()Z after log4j update 
Java :: install java 8 arch 
Java :: java array to list 
Java :: swap function java 
Java :: java run shell command 
Java :: murtaza jafari 
Java :: how to read a string after an integer in java 
Java :: java print two dimensional array 
Java :: java filedialog 
Java :: how to set list data to android spinner 
Java :: recyclerview stop scrolling 
Java :: java game 
Java :: how to declare array java 
Java :: how to initialise array in java without size 
Java :: java get sub array 
Java :: java random unique number 
Java :: set visible gui java 
Java :: inline arraylist initialization java 
Java :: java check if enum contains value 
Java :: get type java 
Java :: jacoco code coverage 
Java :: view get text android 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =