×

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

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.