Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently find the highest power of 2 dividing a given number, in Java?

/*
	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 :: java convert list to page 
::  
::  
Java ::  
Java :: Copying Arrays Using copyOfRange() method Java 
Java :: how to create a random number in java 
:: hibernate select count 
:: how to convert int array to integer list in java 
Java :: java if one sting on array match 
::  
Java ::  
Java :: encode file to base64 java 
::  
::  
::  
Java :: create method setsupportactionbar 
:: java run system command 
:: java shutdown hook 
:: scanner check if int 
:: java settimeout 
::  
Java :: Loop Structure in Java 
::  
Java :: hashmap foreach 
::  
::  
Java :: java foreach arraylist 
:: counting nodes in binary search tree 
::  
::  
ADD CONTENT
Topic
Content
Source link
Name
7+6 =