×

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not.

Sparse Numbers

Any number with binary representation lacks two or more continuous set bits is said to be sparse number.

Let us discuss some examples to be clear about the sparse numbers.

Example1:

Consider an integer n

n = 17

The binary equivalent representation of 17 is 10001.

In the binary representation, the 1’s are not consecutive. Thus 17 is a sparse number.

Example2:

Now consider n = 19

The binary equivalent representation of 19 is 10011.

In the binary representation, the 1’s are consecutive. Thus 19 is not a sparse number.

Example3:

Consider n= 25

The binary equivalent representation of 25 is 11001.

In the binary representation, the 1’s are consecutive. Thus 25 is not a sparse number.

For an integer to know if it is a sparse number or not, we must know the binary number equivalent to the given integer.

So let us first learn to find out the binary equivalent number to the given number.

File name: Binary.java

// Conversion of decimal number to binary number
import java.io.*;
import java.util.*;
class Binary {
static int decimalToBinary(int N)
{


int B_Number = 0;
int cnt = 0;
while (N != 0) {
int rem = N % 2;
double c = Math.pow(10, cnt);
B_Number += rem * c;
N /= 2;
cnt++;
}


return B_Number;
}
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
int N = s.nextInt();;
System.out.println("Decimal - " + N);
System.out.print("Binary - ");
System.out.println(decimalToBinary(N));
}
}

Output

Decimal - 6
Binary - 110
Decimal - 63
Binary – 111111

Now let us understand the process of verifying if a number is a sparse number. For that there are certain approaches that must be followed.

Approach

  • Using an ArrayList
  • Using Right Shift Operators

Using an ArrayList

The binary equivalent of the number can be stored in an array list, which can then be traversed to determine whether the two next elements in the array list possess 1 or not. The provided number will not be a sparse number if it consists two consecutive ones. Else, it is.

Let us look at the below program to understand.

File name: Sparse1.java

import java.util.ArrayList;  
  
public class Sparse1  
{  
  
// a technique that determines whether or not the integer n is indeed a sparse number
public boolean isSparseNum(int n)  
{  
ArrayList<Integer> al = new ArrayList<Integer>();  
while(n != 0)  
{  
    al.add(n % 2);  
    n = n / 2;  
}  
  
int size = al.size();  
for(int i = 0; i < size - 1; i++)  
{  
    // determining whether or not the two successive items are 1
    if((al.get(i) == al.get(i + 1)) && (al.get(i) == 1))  
    {  
        return false;  
    }  
}  
  
return true;  
  
}  
  public static void main(String[] argvs)  
{  
Sparse1 obj = new Sparse1();  
  
int range = 25;  
  
System.out.println("The Spare numbers lying between 1 to " + range + " are: ");  
  
for(int i = 1; i <= range; i++)  
{  
    if(obj.isSparseNum(i))  
    {  
        System.out.print(i + " ");  
    }  
}  
  
}  
}  

Output

The Sparse numbers between 1 to 25 are:
1 2 4 5 8 9 10 16 17 18 20 21

Using Right Shift Operator

To compute the sparse number, we can utilize the right shift operator. We will use this attribute to estimate the sparse number because we are aware that two subsequent bits cannot be set. If we pay close attention, we will see that determining whether a number seems to be sparse or not requires using the bitwise AND of both binary equivalent of the "provided number" and the "right-shifted number" (i.e., half the supplied number). If a number is sparse, the AND operator's output would be 0, and if it is not sparse, it would be non-zero.

File name: Sparse2.java

// Java code to determine whether or not a specific number is sparse
import java.util.*;
class Sparse2 {
// Returns true if it a sparse number else false
static int checkSparse(int n)
{
if ((n & (n >> 1)) >= 1)
return 0;
                                        return 1;
}
public static void main(String[] args)
{
System.out.println(checkSparse(19));
System.out.println(checkSparse(56));
System.out.println(checkSparse(17));
System.out.println(checkSparse(30));
}
}

Output

0
0
1
0

Related Topics

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.