w3resource

Java Exercises: Check whether an given integer is power of 2 or not using O(1) time

Java Basic: Exercise-205 with Solution

Write a Java program to check whether an given integer is power of 2 or not using O(1) time.

Note: O(1) means that it takes a constant time, like 12 nanoseconds, or two minutes no matter the amount of data in the set.
O(n) means it takes an amount of time linear with the size of the set, so a set twice the size will take twice the time. You probably don't want to put a million objects into one of these.

Visualization of powers of two from 1 to 1024:

Java Basic Exercises: Visualization of powers of two from 1 to 1024.

Sample Solution:

Java Code:

import java.util.*;
public class Main 
 {
 public static void main(String[] args)
  {
      boolean b = true;
      Scanner in = new Scanner(System.in);
      System.out.print("Input a number : ");
      int num = in.nextInt();           
     {   
     while(num!=1)
      {
        if(num%2!=0)
          { 
            b=! b;
            System.out.print(b);
            System.exit(0);
          }
            num = num / 2;
      }
       System.out.print(b);
     }
  }
         
}

Sample Output:

Input a number :  25
false

Flowchart:

Flowchart: Java exercises: Check whether an given integer is power of 2 or not using O(1) time.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to compute xn % y where x, y and n are all 32bit integers.
Next: Write a Java program to find all unique combinations from a collection of candidate numbers. The sum of the numbers will be equal to a given target number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK