java programs – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Fri, 10 Nov 2023 18:05:43 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 java programs – Java2Blog https://java2blog.com 32 32 Star Pattern programs in Java https://java2blog.com/star-pattern-java/?utm_source=rss&utm_medium=rss&utm_campaign=star-pattern-java https://java2blog.com/star-pattern-java/#respond Sat, 08 May 2021 11:58:39 +0000 https://java2blog.com/?p=14083 In this article, we will see how to print star pattern in java. Pattern printing programs are good for logic building in programming. We will discuss different types of Star pattern and see the logic behind printing it.

Square Star Pattern in java

Given a number n, we need to print a Square Star Pattern with n number of rows and columns, as in a Square the length of each side is same. Let us look at the program.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // Inner loop for printing '*' in each column.
          for(int j=0;j<n;j++)
          {
              // We add two spaces to match shape of a square.
              System.out.print("*  ");
          }
          System.out.println();
      }
  }
}

Output:

*  *  *  *  *  
*  *  *  *  *  
*  *  *  *  *  
*  *  *  *  *  
*  *  *  *  *

Hollow Square Star Pattern in java

Now, this pattern is more or less same as above, the condition is we print ‘*’ only at the boundaries of the Square. Otherwise we print space. Let us look at the code.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // Inner loop for printing '*' in each column.
          for(int j=0;j<n;j++)
          {
              // For first row and last row we print '*' and for every other row we print the '*' at boundary region. 
              if(i==0 || i==n-1 || j==0 || j==n-1)
              {
              System.out.print("*  ");
              }
              // Otherwise we print blank space.
              else
              System.out.print("   ");
          }
          System.out.println();
      }
  }
}

Output:

*  *  *  *  *  
*           *  
*           *  
*           *  
*  *  *  *  *

Hollow Square Pattern with Diagonal in java

Now, this pattern is same as above, along with the hollow square we need to print ‘*’ along each diagonal. When the value of row and column index are equal we print ‘*’otherwise we print blank space. Let us look at the code:

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 7;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // Inner loop for printing '*' in each column.
          for(int j=0;j<n;j++)
          {
              // We check for major and minor diagonal and print * for each such cell .
              if(i==0 || i==n-1 || j==0 || j==n-1 || i == j || j == n-i-1)
              {
              System.out.print("*  ");
              }
              // Otherwise we print blank space.
              else
              System.out.print("   ");
          }
          System.out.println();
      }
  }
}

Output:

*  *  *  *  *  *  *  
*  *           *  *  
*     *     *     *  
*        *        *  
*     *     *     *  
*  *           *  *  
*  *  *  *  *  *  *

Rhombus Star Pattern in java

Given n number of rows, we need to print a Rhombus Star Pattern. Let us look at the program.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // Print Spaces before each row
          for(int k=0;k<n-i;k++)
          {
            System.out.print("  ");
          }
          // printing '*' in each column.
          for(int j=0;j<n;j++)
          {
            System.out.print("*  ");
          }
          System.out.println();
      }
  }
}

Output:

*  *  *  *  *  
        *  *  *  *  *  
      *  *  *  *  *  
    *  *  *  *  *  
  *  *  *  *  *

Note: If we want to print its Mirror, then in the loop which prints Spaces we change the Loop Condition from k < n – i to k < i.

Right Angled Triangle Star Pattern in java

We need to print a Right Angled Triangle for a given number of rows.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // printing '*' in each column.
          for(int j=0;j<=i;j++)
          {
            System.out.print("* ");
          }
          System.out.println();
      }
  }
}

Output:

* 
* * 
* * * 
* * * * 
* * * * *

Hollow Mirrored Right Angled Triangle Star Pattern in java

We will print the Right Angled Triangle like above but we will print the Mirror of it with ‘*’ pattern along the boundary and the inside will be hollow.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 6;
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          //This prints spaces before each row.
          for(int k=i;k<n;k++)
          System.out.print("  ");

          // printing '*' in each column.
          for(int j=0;j<n;j++)
          {
            // We print '*' for only first and last column and for last row.
            if(j==0 || j==i || i==n-1)
            System.out.print(" *");
            // Otherwise we print Blank Space
            else
            System.out.print("  ");
          }

          System.out.println();
      }
  }
}

Output:

*          
           * *        
         *   *      
       *     *    
     *       *  
   * * * * * *

Hollow Inverted Right Angled Triangle star Pattern in java

We will print the Inverted Right Angle Triangle which will be hollow from inside for a given number of rows. So, we will again print only the boundary of the inverted triangle. Let us look at the code.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 7;  // Number of rows.

      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // printing '*' in each column.
          for(int j=n;j>i;j--)
          {
            // We print '*' for only first and last column and for first row.
            if(j==n || j==i+1 || i==0)
            System.out.print("* ");
            // Otherwise we print Blank Space
            else
            System.out.print("  ");
          }

          System.out.println();
      }
  }
}

Output:

* * * * * * * 
*         * 
*       * 
*     * 
*   * 
* * 
*

Equilateral Triangle Star Pattern in java

For a given number of rows, we print an Equilateral triangle where each row will have same number of stars as the row number. E.g. Row 1 will have 1 Star, Row 2 will have 2 Stars and so on. Let us look at the code for this:

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;  // Number of rows.

      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          for(int k=i;k<n;k++)
          System.out.print(" ");

          // printing '*' in each column.
          for(int j=0;j<=i;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }
  }
}

Output:

* 
    * * 
   * * * 
  * * * * 
 * * * * *

Pyramid Star Pattern in java

For a given number of rows, we have to print the Pyramid Star Pattern. The first Row will have only 1 star, every other row will have No. of stars = Stars in Previous Row + 2. Example: Row 2 will have 3 Stars. Row 3 will have 5 stars and so on. The code is shown below:

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 6;  // Number of rows.

      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          for(int k=i;k<n;k++)
          System.out.print("  ");

          // We run loop till j = 2*i to print odd no. of stars.
          for(int j=0;j<=2*i;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }
  }
}

Output:

* 
          * * * 
        * * * * * 
      * * * * * * * 
    * * * * * * * * * 
  * * * * * * * * * * *

Inverted Pyramid Star Pattern in java

We will print the Inverted version of the above pattern, for n number of rows. The catch is we need a decremental loop here while printing ‘*’ for each row. Let us now look at the program for it.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;  // Number of rows.

      //Outer Loop for number of Rows
      for(int i=n;i>0;i--)
      {
          for(int k=i;k<n;k++)
          System.out.print("  ");

          // We run loop from j = 2*i to 2 print odd no. of stars.
          for(int j=2*i;j>1;j--)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }
  }
}

Output:

* * * * * * * * * 
  * * * * * * * 
    * * * * * 
      * * * 
        *

Hollow Pyramid Star Pattern in java

For n number of rows, we print the Pyramid Pattern. Now, the pattern will be hollow so it will cover only the boundary regions of the Pyramid. Let us look at the code for this.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 8;  // Number of rows.

      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          for(int k=i;k<n;k++)
          System.out.print("  ");

          // We run loop till j = 2*i to print odd no. of stars.
          for(int j=0;j<=2*i;j++)
          {
            // We print '*' for first and last column of each row.
            // and complete for the last row 
            if(j==0 || j==2*i || i==0 || i==n-1)
            System.out.print("* ");
            // Or we print blank space
            else
            System.out.print("  ");
          }

          System.out.println();
      }
  }
}

Output:

* 
              *   * 
            *       * 
          *           * 
        *               * 
      *                   * 
    *                       * 
  * * * * * * * * * * * * * * *

Half-Diamond Star Pattern in java

We need to print a Half Diamond pattern for a given number of rows. If we breakdown this problem we need to print a Right Angled Triangle for n rows and then print the Inverted Right Angled triangle for n-1 rows. Let us look at the program to print such a pattern.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 5;  // Number of rows.

      // We first print Right Angled Triangle
      //Outer Loop for number of Rows
      for(int i=0;i<n;i++)
      {
          // printing '*' in each column.
          for(int j=0;j<=i;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }

      // Then we print Inverted Right Angled Triangle
      for(int i=0;i<n-1;i++)
      {
          for(int j=i;j<n-1;j++)
          {
              System.out.print("* ");
          }
          System.out.println();
      }
  }
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Diamond Star Pattern in java

We have to print a Diamond Star Pattern for n (n is Odd) number of rows. In simpler terms, we need to print a Pyramid Pattern for n/2 +1 rows (as n is odd), then we print Inverted Pyramid Pattern for the remaining half of the rows. Let us look at the code.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 7;  // Number of rows.

      n= n/2 + 1;
      int i=0;
      //We first print Pyramid Pattern
      for(i=0;i<n;i++)
      {
          for(int k=i;k<n;k++)
          System.out.print("  ");

          // We run loop till j = 2*i to print odd no. of stars.
          for(int j=0;j<=2*i;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }

      n=i;  // i=n-1 so copy its value to n.

      // We then print Inverted Pyramid Traingle.
      for(i=n-1;i>0;i--)
      {
          // We need to print one space for first row.
          for(int k=i;k<n+1;k++)
          System.out.print("  ");

          // We run loop from j = 2*i to 2 print odd no. of stars.
          for(int j=2*i;j>1;j--)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }

          System.out.println();
      }

  }
}

Output:

* 
      * * * 
    * * * * * 
  * * * * * * * 
    * * * * * 
      * * * 
        *

Left Arrow Star Pattern in java

For a given n number of rows (n is strictly Odd) we have to print a Left Arrow Star Pattern. The logic we use will be same as used in printing Right angled triangle Pattern and we maintain indentation while printing each row. Let us look at the code.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 11;  // Number of rows.
      
      n = n/2 + 1;
      
      int i=0;
      
      //We first print Upper Part using Right Angled Logic.
      for(i=0;i<n;i++)
      {
          // We avoid space for last row with 1 star
          for(int k=i;k<n-1;k++)
          System.out.print("  ");
          
          // No. of '*' for each row changes with i.
          for(int j=i;j<n;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }
          
          System.out.println();
      }
      
      n=i;  // i=n so copy its value to n.
      
      // We then print Lower Part of Pattern.
      // The lower part always start with 2 stars in first row so we set m=2.
      int m=2;
      for(i=n;i>1;i--)
      {
          // We need to print one space for first row.
          for(int k=i;k<n+1;k++)
          System.out.print("  ");
          
          // We increment m after this loop to continue printing stars equal to row number.
          for(int j=0;j<m;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }
          m++;
          System.out.println();
      }
        
  }
}

Output:

* * * * * * 
        * * * * * 
      * * * * 
    * * * 
  * * 
* 
  * * 
    * * * 
      * * * * 
        * * * * * 
          * * * * * *

Right Arrow Star Pattern in java

Like the above pattern, given n number of rows (n is strictly Odd) we have to print a Right Arrow Star Pattern. The logic we use will be same as used in printing Inverted Right angled triangle Pattern and we maintain indentation while printing each row. Let us look at the program to print such pattern.

public class PatternExercise
{
  public static void main(String args[]) 
  {
      int n = 9;  // Number of rows.
      
      n = n/2 + 1;
      
      int i=0;
      
      //We first print Upper Part using Inverted Right Angled Logic.
      for(i=0;i<n;i++)
      {
          // We avoid space for first row
          for(int k=0;k<i;k++)
          System.out.print("  ");
          
          // No. of '*' for each row changes with i.
          for(int j=i;j<n;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }
          
          System.out.println();
      }
      
      n=i;  // i=n so copy its value to n.
      
      // We then print Lower Part of Pattern.
      // The lower part always start with 2 stars in first row so we set m=2.
      int m=2;
      for(i=0;i<n-1;i++)
      {
          // We avoid blank space for last row.
          for(int k=i;k<n-2;k++)
          System.out.print("  ");
          
          // We increment m after this loop to continue printing stars equal to row number.
          for(int j=0;j<m;j++)
          {
            // We print '*' for each row.
            System.out.print("* ");
          }
          m++;
          System.out.println();
      }
        
  }
}

Output:

* * * * * 
  * * * * 
    * * * 
      * * 
        * 
      * * 
    * * * 
  * * * * 
* * * * *

Cross or X Star Pattern in java

Given n number of rows we need to print a Cross or X Star Pattern of 2*n -1 rows. For Ex: If the Number of Rows given in Input = 9, then we need to print a X Star Pattern with 17 (2*n-1) rows . The program for it is shown below:

public class PatternExercise
{
  public static void main(String args[]) 
  {
    int n = 8;  // Number of rows.
      
    int m = 2*n-1; // So we need to print total 15 rows.
    
    // Outer loop for number of rows.
    for(int i=1;i<=m;i++)  
    {  
      for(int j=1;j<=m;j++)  
      {  
       // for each row we print * for the first and last column.      
       if(i==j || j==(m-i+1))  
       {  
         System.out.print("*");  
       }  
       // otherwise we print blank space.
       else  
       System.out.print(" ");  
    }  
    
    System.out.println();  
    }  
        
  }
}

Output:

*             *
 *           * 
  *         *  
   *       *   
    *     *    
     *   *     
      * *      
       *       
      * *      
     *   *     
    *     *    
   *       *   
  *         *  
 *           * 
*             *

Hollow Diamond Star Pattern in java

Given n number of rows, we need to print a Hollow Diamond Star pattern enclosed within a block of 2*n number of rows. So, for 5 rows the Program should print 10 rows of Star pattern enclosing a Hollow Diamond. Let us look at the code for it.

public class PatternExercise
{
  public static void main(String args[]) 
  {
    int n = 6;  // Number of rows.
      
    // Print upper half of pattern  
    for(int i=1; i<=n; i++)
    {
        // We print left side stars.
        for(int j=i; j<=n; j++)
        {
            System.out.print("*");
        }
        // Then print spaces , first row has one blank space
        for(int j=1; j<=(2*i-1); j++)
        {
            System.out.print(" ");
        }
        // then we print right side stars.
        for(int j=i; j<=n; j++)
        {
            System.out.print("*");
        }

        System.out.println();
    }

    // Loop to print lower half of the pattern
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=i; j++)
        {
            System.out.print("*");
        }
        // Here we decrease no. of blank spaces after each printing each row.
        for(int j=(2*i-2); j<(2*n-1); j++)
        {
            System.out.print(" ");
        }

        for(int j=1; j<=i; j++)
        {
            System.out.print("*");
        }

        System.out.println();
    }

        
  }
}

Output:

****** ******
*****   *****
****     ****
***       ***
**         **
*           *
*           *
**         **
***       ***
****     ****
*****   *****
****** ******

Christmas Tree Star Pattern in java

For a given height h, we need to print a Christmas Tree Pattern. The pattern consists of h Pyramids which will shape the upper tree and at the end we print the trunk or branch of the tree of h-1 height. Let us look at the code to print this pattern.

class Pattern_ChristmasTree
{
  public static void main(String[] args) 
  {
	//Value 4 is height of tree or total pyramids to print.
    int height = 4;

	//Assigning Width which is width of each pyramid.
	int width = 4;

	//Assigning Space
	// These spaces will be printed before each pyramid.
	int space = width * height;

	int x = 1;

	//Code to Print Upper Part of the Tree i.e. Pyramids.
	for(int a = 1;a <= height ;a++)
        {
	  for(int i = x;i <= width;i++)
	  {

	   for(int j = space;j >= i;j--)
	   {
		System.out.print(" ");
	   }

	   for(int k = 1;k <= i;k++)
	   {
		System.out.print("* ");
	   }

	   System.out.println();
	  }
        // we increase x and width for printing each pyramid.
	x = x+2;
	width = width+2;
	}

	//Printing Branch or trunk of Christmas Tree
	// we run loop till i = 3 i.e. height -1.
	for(int i = 1;i <= height-1;i++)
	{
         // we can also initailize j = space - height - 1.
	  for(int j = space-3;j >= 0;j--)
	  {
	   	System.out.print(" ");
	  }

	  for(int k= 1;k <= height-1;k++)
	  {
		 System.out.print("* ");
	  }

	System.out.println();
	}
}
}

Output:

* 
               * * 
              * * * 
             * * * * 
              * * * 
             * * * * 
            * * * * * 
           * * * * * * 
            * * * * * 
           * * * * * * 
          * * * * * * * 
         * * * * * * * * 
          * * * * * * * 
         * * * * * * * * 
        * * * * * * * * * 
       * * * * * * * * * * 
              * * * 
              * * * 
              * * *

So that’s it for the article you can try out the above examples with different inputs to test your understanding. You can leave your suggestions or doubts in comment section below.

]]>
https://java2blog.com/star-pattern-java/feed/ 0
Convert Roman Number to Integer in Java https://java2blog.com/convert-roman-number-to-integer-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-roman-number-to-integer-java https://java2blog.com/convert-roman-number-to-integer-java/#respond Sat, 17 Apr 2021 05:03:23 +0000 https://java2blog.com/?p=13919 1. Introduction

In this article, we look into an interesting problem: How to convert Roman Number to Integer in Java.

Roman numerals are represented by seven different symbols : I, V, X, L, C, D, M. The Integral values associated with each symbol is shown in the table below:

Roman Symbol Value
I1
V5
X10
L50
C100
D500
M1000

Usually, roman numbers are written from left to right, which makes it easier for us to scan each roman character and add the corresponding value for each character to get the result.

For Example: Roman Number III has Integral value is 3 adding value of three I’s together (1+1+1=3).

Similarly for Roman Number: DCLXVI , Its integer value is : 500 + 100 + 50 + 10 +5 + 1= 666.

However, the Roman Number for 4 and 9 are not written as IIII and VIIII, respectively. They are written as IV which is (5-1 = 4), and for 9 it is IX (10 -1=9). This case is for letter I. There are 2 more cases to consider:

  • X can be placed before L (50) and C (100), like XL and XC to make 40 and 90 respectively.
  • Similarly, C can be placed before D and M, like CD and CM to make 400 and 900, respectively. 

Hence, for Roman Number ‘CDXLIX’ the integer is 449.

Note: If a Roman Symbol having smaller value precedes a Symbol with Higher Value, we need to subtract the higher value from the smaller value to get the result. Roman Numbers can have maximum Integral value: 3999 represented as : MMMCMXCIX.

We will implement conversion in two parts:

  • Validate the given Roman number.
  • If Roman number is in correct format, convert it into integer.

2. Validate Roman number using regex

We need to put some validation logic to ensure that input String is a valid roman numeral. One of the approaches to validate it using regular expression.

Here is regular expression which we can use to validate:

^M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$

This regular expression matches a string that starts with zero or more M’s, followed by either CM, CD, or D followed by zero to three C’s, followed by either XC, XL, or L followed by zero to three X’s, followed by either IX, IV, or V followed by zero to three I’s, and ends with the end of the string. This covers all the possible combinations of Roman numerals from 1 to 3999.

We can use matches() method of String class to check if input string matches the regular expression. If it doesn’t match we can throw an exception.

// Define the regular expression for valid Roman numerals
   String regex = "^M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";

   // Check if the input string matches the regular expression
   if (!roman.matches(regex)) {
      // Throw an exception or return an error message
      throw new IllegalArgumentException("Invalid Roman numeral: " + roman);
   }

3. Using Java 8 Stream

To convert roman number to Integer

  • Create a map with Roman Symbol as key and its corresponding value as value.
  • Declare a variable named result and assign it to zero. This variable will store the final result of the conversion.
  • Create a Stream using IntStream.range() to iterate over characters of Input String.
  • Compare current and next characters such that:
    • If the current character is smaller than the next character, it means that the current character should be subtracted from the result. For example, in XLVII, the X is smaller than the L, so it should be subtracted from the result.
    • Otherwise, if the current character is equal to or larger than the next character, it means that the current character should be added to the result. For example, in XLVII, the L is equal to the L, so it should be added to the result.
package org.arpit.java2blog.generic;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

class RomanToInteger
{

    public static int romanToInteger(String roman)
    {
        // Define the regular expression for valid Roman numerals
        String regex = "^M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";

        // Check if the input string matches the regular expression
        if (!roman.matches(regex)) {
            // Throw an exception or return an error message
            throw new IllegalArgumentException("Invalid Roman numeral: " + roman);
        }

        Map<Character,Integer> numbersMap = new HashMap<>();
        numbersMap.put('I',1);
        numbersMap.put('V',5);
        numbersMap.put('X',10);
        numbersMap.put('L',50);
        numbersMap.put('C',100);
        numbersMap.put('D',500);
        numbersMap.put('M',1000);

        // local variable
        final int[] result = {0};

        // A stream to iterate over the characters of the string
        IntStream.range(0, roman.length()).forEach(i -> {
            // Get the current and next character
            char c = roman.charAt(i);
            char next = i < roman.length() - 1 ? roman.charAt(i + 1) : ' ';

            // If the current character is smaller than the next, subtract its value
            if (numbersMap.get(c) < numbersMap.getOrDefault(next, 0)) {
                result[0] -= numbersMap.get(c);
            }
            // Otherwise, add its value
            else {
                result[0] += numbersMap.get(c);
            }
        });

        // Return the result
        return result[0];
    }

    public static void main(String args[])
    {
        // we take input as a String
        String romanNumber="MCMXCIV";
        int result = romanToInteger(romanNumber);

        System.out.println("The Roman Number is: "+romanNumber);
        System.out.println("Its Integer Value is: "+result);

        System.out.println();

        romanNumber="DCCXCIX";
        result = romanToInteger(romanNumber);

        System.out.println("The Roman Number is: "+romanNumber);
        System.out.println("Its Integer Value is: "+result);
    }

}

4. Using Traditional if else and for Loop

Here is logic to for converting Roman number to Integer.

  • We will take a HashMap and for each Roman Character, we will put its respective value in the Map as shown in the table above. The Key would be the Roman Symbol and the Value will be the Integral Value of the Symbol.
  • We iterate through each character in the given Number ,For each character we need to consider two cases :
    • Case 1 : If the Character’s value is greater than the previous character value i.e. The condition is : if (Value(charAt(i)) >Value(charAt(i-1)), we need to perform subtraction as : Value(charAt(i)) - 2* Value(charAt(i-1)) ; then add the result to our answer.
    • Case 2: If the Character’s value is lesser than previous one we simply add its corresponding value to our answer and continue the process.
  • In Case 1, we subtract twice the previous character value because we might have already added the value while processing it, so we subtract twice the value.

Now let us have a quick look at the code in Java:

import java.util.*;

class RomanToInteger
{

 public static int romanToInteger(String roman) 
 {
   // Define the regular expression for valid Roman numerals
   String regex = "^M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";

   // Check if the input string matches the regular expression
   if (!roman.matches(regex)) {
      // Throw an exception or return an error message
      throw new IllegalArgumentException("Invalid Roman numeral: " + roman);
   }

    Map<Character,Integer> numbersMap = new HashMap<>();
    numbersMap.put('I',1);
    numbersMap.put('V',5);
    numbersMap.put('X',10);
    numbersMap.put('L',50);
    numbersMap.put('C',100);   
    numbersMap.put('D',500);   
    numbersMap.put('M',1000);  

    int result=0;

    for(int i=0;i<roman.length();i++)
    {
      char ch = roman.charAt(i);      // Current Roman Character

      //Case 1
      if(i>0 && numbersMap.get(ch) > numbersMap.get(roman.charAt(i-1)))
      {
        result += numbersMap.get(ch) - 2*numbersMap.get(roman.charAt(i-1));
      }

      // Case 2: just add the corresponding number to result.
      else
        result += numbersMap.get(ch);
    }

    return result;
 }

 public static void main(String args[])
 {
   // we take input as a String
   String romanNumber="MCMXCIV";
   int result = romanToInteger(romanNumber);

   System.out.println("The Roman Number is: "+romanNumber);
   System.out.println("Its Integer Value is: "+result);

   System.out.println();

   romanNumber="DCCXCIX";
   result = romanToInteger(romanNumber);

   System.out.println("The Roman Number is: "+romanNumber);
   System.out.println("Its Integer Value is: "+result);
 }

}

Output:

The Roman Number is: MCMXCIV
Its Integer Value is: 1994

The Roman Number is: DCCXCIX
Its Integer Value is: 799

5. Time Complexity

The time complexity of this code is O(n), where n is the length of Roman Number in String format as we are traversing String only once.

6. Conclusion

In this article, we implemented a simple java program to convert Roman numeral to Integer. Before the conversion, we have also implemented validation logic to make sure input string is a valid Roman numeral.

]]>
https://java2blog.com/convert-roman-number-to-integer-java/feed/ 0
Count occurrences of Character in String https://java2blog.com/count-number-occurrences-character-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=count-number-occurrences-character-string-java https://java2blog.com/count-number-occurrences-character-string-java/#respond Mon, 05 Apr 2021 17:12:39 +0000 https://java2blog.com/?p=13391 In this article, we will look at a problem: Given an Input String and a Character, we have to Count Occurrences Of character in String.

For Example, If the Given String is : "Java2Blog" and we have to count the occurrences of Character ‘a’ in the String.

Therefore, Count of 'a' is : 2 , in the String “Java2Blog” . We will discuss different approaches to do this :

Note: The search of the Character will be Case-Sensitive for any String.

1. Using String Library Methods

This is the most conventional and easiest method to follow in order to find occurrences of character in a string . For this, we use the charAt() method present in the String Class of java.lang package. The signature of method is :

public char charAt(index) – index of the character to be found.

  • Iterate throughout the length of the input String
  • Check whether each character matches the character to search
    • If yes, increment the count
    • else do nothing
Let us look at the implementation:

public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int count=0;
  for(int i=0; i<input.length(); i++)
  {
      if(input.charAt(i) == search)
      count++;
  }
  
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

2. Using Recursion

This is a rather interesting and tricky solution. Here, we call our function for the start index 0 of the String. If character matches to searched character, we add 1 to our result variable and recur for index+1, until we reach the end point of the string.

Let us look at the code:

public class CountOccurences
{

  static int findOccurrences(String str, char search, int index)
  {
      if(index >= str.length())
      return 0;
      
      int count=0;
      
      if(str.charAt(index) == search)
      count++;
      
      return count + findOccurrences(str,search,index+1);
  }
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbccAAdd";
  char search = 'a';             // Character to search is 'a'.
  
  int result = findOccurrences(input,search,0); //start index 0 for       start of string.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

3. Using Hashing Concept

Using Arrays

In this approach, we use a primitive integer type array of size 26. Then for each character in the string we encounter we increment it’s hash value in the array. For each character, char its index in array will be : Arr[ char – 97].

Note: This is a Case Sensitive Approach. If we use Uppercase Characters the index value will be: Arr[ char – 65]. The space we use is constant does not depend on size of input String.

Let us look at the implementation.

public class CountOccurences
{
   
  public static void main(String args[]) 
  {
 
  String input = "aaaabbcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  int hash_arr[] = new int[26];
  
  for(int i=0;i<input.length();i++)
  {
      hash_arr[input.charAt(i) - 97]++;
  }
  
  int result = hash_arr[search-97]; // we get count value of character from the array.
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Using Collections (Map)

Here we will do the same thing as above for each character in the input string we will put it in our Map with value 1, if it is seen for the first time. If the character repeats or the character is already present in our Map, we update the value of the character in the map by adding 1 to it. We can use any type of Map; HashMap, TreeMap, https://java2blog.com/linkedhashmap-in-java-with-example/. In this example we used a simple HashMap.

Note: This approach works for both Uppercase and Lowercase Characters. Hence, Case In-Sensitive.

import java.util.*;
public class CountOccurences
{
   
  public static void main(String args[]) 
  {
      
  String input = "aaaabbAAAAcccddd";
  char search = 'a';             // Character to search is 'a'.
  
  Map<Character,Integer> hash = new HashMap<Character,Integer>();
  
  for(int i=0;i<input.length();i++)
  {
      if(hash.containsKey(input.charAt(i)))
      hash.put(input.charAt(i), hash.get(input.charAt(i))+1);
      
      else
      hash.put(input.charAt(i), 1);
  }
  
  int result = hash.get(search);
  
  System.out.println("The Character '"+search+"' appears "+result+" times.");
  }
}

Output:

The Character 'a' appears 4 times.

4. Using Java 8 Features

If we use Java 8 or above JDK Version, we can use the feature of lambdas and Stream to implement this. We will use the IntStream class methods, chars() method and codePoints() method which returns the integer codepoints (Unicode value) of the character stream. We will then filter them using Lambda expression with the search character and count their occurrences using count method. We will look at each of their implementation.

import java.util.*;
public class CountOccurences
{
  public static void main(String args[]) 
  {
      
  String input = "aaabbAAAAAcccd";
  char search = 'A';             // Character to search is 'a'.
  
  //Example 1
  long count = input.chars().filter(ch -> ch == search).count();
  // chars() method return integer representation of codepoint values of the character stream
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  
  //Example 2
  count = input.codePoints().filter(ch -> ch == search).count();
  // codePoints() just return the actual codepoint or Unicode values of the stream.
  System.out.println("The Character '"+search+"' appears "+count+" times.");
  
  }
}

Output:

The Character 'A' appears 5 times.
The Character 'A' appears 5 times.

So that’s it for how to count Occurrences Of Character in String, you can try out with other examples and execute the code for better understanding.

]]>
https://java2blog.com/count-number-occurrences-character-string-java/feed/ 0
Rock Paper Scissors Game in Java https://java2blog.com/rock-paper-scissors-game-java/?utm_source=rss&utm_medium=rss&utm_campaign=rock-paper-scissors-game-java https://java2blog.com/rock-paper-scissors-game-java/#respond Wed, 30 Dec 2020 12:09:27 +0000 https://java2blog.com/?p=10677 In this topic, we are going to learn a funtastic game Rock Paper Scissors. You may have played it during childhood. Let’s understand it by using simple steps. We will see Rock Paper Scissors Game implementation using Java.

It is a two player game and contains three main components Rock, Paper and Scissors. Each player has these components and simultaneously chooses either Rock, Paper, or Scissors. It has some rules like:

  1. Rock beats Scissors but loses to Paper.
  2. Paper beats Rock but loses to Scissors.
  3. Scissors beats Paper but loses to Rock.

RockPaperScissors

Read also: Number guessing game in java
Let’s play with the Java program.

import java.util.*;
public class Main
{
    enum Move {
        ROCK,
        PAPER,
        SCISSORS
    }

    public static String getPlayerMove()
    {
        Scanner scan = new Scanner(System.in);
        String choice = scan.next();
        String playerChoice = choice.toUpperCase();
        scan.close();
        if(playerChoice.equals("ROCK") || playerChoice.equals("PAPER") || playerChoice.equals("SCISSORS")){
            return playerChoice;
        }else{
            System.out.println("This is not Valid Move, Try again!");
            return "Bad Input";
        }

    }

    public static String getComputerMove()
    {
        String computerChoice;
        Random random = new Random();
        int input = random.nextInt(3)+1;
        if (input == 1) {
            computerChoice = Move.ROCK.name();
        }
        else if(input == 2) {
            computerChoice = Move.PAPER.name();
        }
        else {
            computerChoice = Move.SCISSORS.name();
        }
        return computerChoice;    
    }

    public static void main(String args[]) 
    {
        System.out.println("Welcome to Rock Paper Game! \nYour's Game partner is Computer. \nEnter Your Move:  ");
        System.out.println("ROCK");
        System.out.println("PAPER");
        System.out.println("SCISSORS");

        String playerMove = getPlayerMove();
        System.out.println("Your move is: "+ playerMove);
        if(!playerMove.equals("Bad Input")) {
            String computerMove = getComputerMove();
            System.out.println("Computer move is: " + computerMove);
            if (playerMove.equals(computerMove)) {
                System.out.println("Game is Tie !!");
            }
            // If playerMove is ROCK         
            else if (playerMove.equals(Move.ROCK.name())) {
                if(computerMove.equals(Move.PAPER.name())) {
                    System.out.println("Computer Wins");
                    System.out.println("Better Luck Next Time!");
                }else {
                    System.out.println("You Win!");
                    System.out.println("OOhhOO, Congratulations!!! ");
                }
            }
            // If playerMove is PAPER
            else if (playerMove.equals(Move.PAPER.name())) {
                if(computerMove.equals(Move.SCISSORS.name())) { 
                    System.out.println("Computer Wins");
                    System.out.println("Better Luck Next Time!");
                }
                else { 
                    System.out.println("You Win!");
                    System.out.println("OOhhOO, Congratulations!!! ");
                }
            }
            // If playerMove is SCISSORS    
            else {
                if(computerMove.equals(Move.ROCK.name())) {
                    System.out.println("Computer Wins");
                    System.out.println("Better Luck Next Time!");
                }
                else { 
                    System.out.println("You Win!");
                    System.out.println("OOhhOO, Congratulations!!! ");
                }
            }
        }
    }
}

Output:

Welcome to Rock Paper Game!
Your’s Game partner is Computer.
Enter Your Move:
ROCK
PAPER
SCISSORS

Rock
Your move is: ROCK
Computer move is: SCISSORS
You Win!
OOhhOO, Congratulations!!!

That’s all about Rock Paper Scissors Game in Java.

]]>
https://java2blog.com/rock-paper-scissors-game-java/feed/ 0
Find automorphic number in java https://java2blog.com/automorphic-number-java/?utm_source=rss&utm_medium=rss&utm_campaign=automorphic-number-java https://java2blog.com/automorphic-number-java/#respond Fri, 25 Dec 2020 18:19:03 +0000 https://java2blog.com/?p=11395 In this post, we will see how to find automorphic number in java.

Automorphic number are those natural numbers whose square ends in same digits are number itself.

25 is automorphic number because:
square of 25 is 625 and 625 ends with same digits as original number 25.

76 is automorphic number because:
square of 76 is 5776 and 5776 ends with same digits as original number 76.

Find automorphic number using digits

Here is simple algorithm to find automorphic number using digits.

  • Take value of n from user using Scanner class
  • Find square of n sqrOfN
  • Count number of digits noOfDigits in n
  • Find last noOfDigits of sqrOfN and assign it to lastNDigitsOfSquare
  • Check if lastNDigitsOfSquare is equal to n
    • If yes, then number is automorphic
    • If no, then number is not automorphic

package org.arpit.java2blog;

import java.util.Scanner;

public class AutomorphicNumberMain {

    public static void main(String args[]){

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = in.nextInt();

        boolean isAutomorphicNumber = isAutomorphicNumber(n);
        if(isAutomorphicNumber)
        {
            System.out.println(n +" is automorphic number");
        }
        else
        {
            System.out.println(n +" is not automorphic number");
        }
    }

    private static boolean isAutomorphicNumber(int n) {
        int noOfDigits=0;
        int sqrOfN = n * n;
        System.out.println("Square of n is: "+sqrOfN);
        int temp = n;  //copying num

        // count digits of num
        while(temp>0){
            noOfDigits++;
            temp=temp/10;
        }

        int lastNDigitsOfSquare = (int) (sqrOfN%(Math.pow(10,noOfDigits)));

        if(n == lastNDigitsOfSquare)
            return true;
        else
           return false;
    }
}

Output:

Enter a number
76
Square of n is: 5776
76 is automorphic number

Find automorphic number using String

We can also use String’s endsWith() method to find automorphic number using String.
Here is simple algorithm to find automorphic number using digits.

  • Take value of n from user using Scanner class and convert it to String numStr
  • Find square of n and convert it to String sqrNumStr
  • Check if sqrNumStr with numStr
    • If yes, then number is automorphic
    • If no, then number is not automorphic

package org.arpit.java2blog;

import java.util.Scanner;

public class AutomorphicNumberUsingString {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = in.nextInt();

        boolean isAutomorphicNumber = isAutomorphicNumberUsingString(n);
        if(isAutomorphicNumber)
        {
            System.out.println(n +" is automorphic number");
        }
        else
        {
            System.out.println(n +" is not automorphic number");
        }
    }

    // Check automorphic number using String
    public static boolean isAutomorphicNumberUsingString(int n) {

        // convert numbers to string
        String numStr = Integer.toString(n);
        String sqrNumStr = Integer.toString(n*n);
        System.out.println("Square of n is: "+sqrNumStr);
        // check endWith
        if(sqrNumStr.endsWith(numStr))
            return true;

        return false;
    }
}

Output:

Enter a number
25
Square of n is: 625
25 is automorphic number

Find automorphic number in range

We can simply use a for loop to iterate from minimum to maximum range interval and check if number is automorphic or not.

package org.arpit.java2blog;

import java.util.Scanner;

public class AutomorphicNumberRange {

    public static void main(String[] args) {
        int min = 0, max = 0;

        Scanner scanner = new Scanner(System.in);

        // Get min and max values
        System.out.print("Enter minimum range: ");
        min = scanner.nextInt();
        System.out.print("Enter maximum range ");
        max = scanner.nextInt();

        // check number
        System.out.println("The Automorphic numbers from "+
                min+" to "+ max+" are: ");

        for(int i=min; i<=max; i++) {
            if(isAutomorphicNumber(i))
                System.out.print(i+" ");
        }

        // close Scanner class object
        scanner.close();
    }

    private static boolean isAutomorphicNumber(int n) {
        int noOfDigits=0;
        int sqrOfN = n * n;
        int temp = n;  //copying num

        // count digits of num
        while(temp>0){
            noOfDigits++;
            temp=temp/10;
        }

        int lastNDigitsOfSquare = (int) (sqrOfN%(Math.pow(10,noOfDigits)));

        if(n == lastNDigitsOfSquare)
            return true;
        else
            return false;
    }
}

Output:

Enter minimum range: 5
Enter maximum range 100
The Automorphic numbers from 5 to 100 are:
5 6 25 76

That’s all about how to find automorphic number in java.

]]>
https://java2blog.com/automorphic-number-java/feed/ 0
Find nth prime number in java https://java2blog.com/nth-prime-number-java/?utm_source=rss&utm_medium=rss&utm_campaign=nth-prime-number-java https://java2blog.com/nth-prime-number-java/#respond Fri, 25 Dec 2020 17:16:41 +0000 https://java2blog.com/?p=11385 In this post, we will see how to find nth Prime number in java.

What is prime number

Prime number is a number that is greater than 1 and divided by 1 or itself.
For example: 5, 7, 13, 23

We have already seen how to check if number is prime or not. We will use same method to find nth prime number in java.

Nth prime number in java

Here are steps to find nth prime number in java.

  • Take value of n from user using Scanner class.
  • Intialize a variable count. It will keep track of number of prime number processed so far.
  • Intialize a variable i. It will keep track of current number.
  • Iterate over while loop until count ! = n
    • Increment i by 2 as even numbers are not prime
    • Check if number is prime. If number is prime then increment count by 1.
  • Return i which is nth prime number.

package org.arpit.java2blog;

import java.util.Scanner;

public class NthPrimeNumberJava {

    public static void main(String args[]){

        Scanner in = new Scanner(System.in);

        //Input the value of 'n'
        System.out.println("Enter the value of n");
        int n= in.nextInt();

        int nthPrimeNumber = findNthPrimeNumber(n);
        System.out.println("Nth Prime Number is: "+nthPrimeNumber);
    }

    private static int findNthPrimeNumber(int n)
    {
        if(n==1)
        {
            return 2;
        }

        int i=1;
        int count=1;
        //While loop should run until we find nth prime number i.e (count != n)
        while(count != n){
            // increment number by 2 as even numbers are always not prime
            i+=2;

            if(isPrime(i))
                count++;  // increment the count when we get prime number
        }
        // return nth prime number
        return i;
    }

    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Output:

Enter the value of n
24
Nth Prime Number is: 89

That’s all about how to find nth prime number in java.

]]>
https://java2blog.com/nth-prime-number-java/feed/ 0
How to capitalize first letter in java https://java2blog.com/capitalize-first-letter-java/?utm_source=rss&utm_medium=rss&utm_campaign=capitalize-first-letter-java https://java2blog.com/capitalize-first-letter-java/#respond Thu, 24 Dec 2020 17:56:45 +0000 https://java2blog.com/?p=11250 In this post, we will how to capitalize first letter in java

Capitalize first letter of String

Here are the steps to convert first letter of string to uppercase in java

  • Get first letter of String firstLetStr using str.substring(0,1).
  • Get remaining String remLetStr using str.substring(1).
  • Convert first letter of String firstLetStr to upper Case using toUpperCase() method.
  • Concatenate both the String firstLetStr and remLetStr.

package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {

        // create a string
        String name = "java2blog";
        System.out.println("Original String: " + name);
        // get First letter of the string
        String firstLetStr = name.substring(0, 1);
        // Get remaining letter using substring
        String remLetStr = name.substring(1);

        // convert the first letter of String to uppercase
        firstLetStr = firstLetStr.toUpperCase();

        // concantenate the first letter and remaining string
        String firstLetterCapitalizedName = firstLetStr + remLetStr;
        System.out.println("String with first letter as Capital: " + firstLetterCapitalizedName);

    }
}

Output:

Original String: java2blog
String with first letter as Capital: Java2blog

Capitalize first letter of each word

Here are the steps to capitalize first letter of each word.

  • Split String by space and assign it String array words
  • Iterate over the String array words and do following:
    • Get first letter of String firstLetter using str.substring(0,1).
    • Get remaining String remainingLetters using str.substring(1).
    • Convert first letter of String firstLetter to upper Case using toUpperCase() method.
    • Concatenate both the String firstLetter and remainingLetters.

package org.arpit.java2blog;

public class CapitalizeFirstLetterMain {
    public static void main(String[] args) {
        // create a string
        String str = "this is java code";
        String words[]=str.split("\\s");
        String capitalizeStr="";

        for(String word:words){
            // Capitalize first letter
            String firstLetter=word.substring(0,1);
            // Get remaining letter
            String remainingLetters=word.substring(1);
            capitalizeStr+=firstLetter.toUpperCase()+remainingLetters+" ";
        }
        System.out.println(capitalizeStr);
    }
}

Output:

This Is Java Code

That’s all about How to capitalize first letter in java.

]]>
https://java2blog.com/capitalize-first-letter-java/feed/ 0
Find first and last digit of a number https://java2blog.com/java-program-find-first-last-digit-number/?utm_source=rss&utm_medium=rss&utm_campaign=java-program-find-first-last-digit-number https://java2blog.com/java-program-find-first-last-digit-number/#comments Fri, 09 Oct 2020 12:30:26 +0000 https://java2blog.com/?p=10870 In this article, we are going to find first and last digit of a number.
To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log() methods of Math class etc.

Let’s see some examples.
Before moving to example, let’s first create an algorithm to find first and last digit of a number.

Algorithm

Step 1: Take a number from the user.
Step 2: Create two variables firstDigit and lastDigit and initialize them by 0.
Step 3: Use modulo operator(%) to find last digit.
Step 4: Use either while loop and division operator (/) or log() and pow() methods of Math class to find

.
Step 5: Display the result.

Using while loop

It is easy to use modulo operator that will return the last digit of the number, and we can use while loop and division operator to get first digit of number.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;

        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);

        while(number!=0) {
            firstDigit = number%10;
            number /= 10;
        }
        System.out.println("First digit: "+firstDigit);
    }
}

Output

Last digit: 7
First digit: 5

Using log() and pow() methods

If we want to use built-in methods like log() and pow() of Math class, then we can use log() method to get the number of digits and pow() method to get divisor value that later on used to get the first digit of number. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;

        // find last digit
        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);

        int digits = (int)(Math.log10(number)); 
        // Find first digit 
        firstDigit = (int)(number / (int)(Math.pow(10, digits)));
        System.out.println("First digit: "+firstDigit);
    }
}

Output

Last digit: 7
First digit: 5

Using while loop and pow() method

If we don’t want to use log() method then use while loop to count the number of digits and use that count into the pow() method to get divisor. See the example below.

public class Main
{   
    public static void main(String args[]) 
    {   
        int number = 502356997;
        int firstDigit = 0;
        int lastDigit = 0;
        int count = 0;

        lastDigit = number%10;
        System.out.println("Last digit: "+lastDigit);
        int n = number;
        while(n!=0) {
            count++;
            n = n/10;
        }
        firstDigit = number/(int)Math.pow(10, count-1);
        System.out.println("First digit: "+firstDigit);
    }
}

Output:

Last digit: 7
First digit: 5

That’s all about how to find first and last digit of number.

]]>
https://java2blog.com/java-program-find-first-last-digit-number/feed/ 1
Happy Number program in Java https://java2blog.com/happy-number-program-java/?utm_source=rss&utm_medium=rss&utm_campaign=happy-number-program-java https://java2blog.com/happy-number-program-java/#respond Sat, 03 Oct 2020 05:57:52 +0000 https://java2blog.com/?p=10681 In this article, we are going to learn to find Happy Number using Java. Let’s first understand, what is Happy Number?

What is a Happy Number?

A number which leaves 1 as a result after a sequence of steps and in each step number is replaced by the sum of squares of its digit. For example, if we check whether 23 is a Happy Number, then sequence of steps are

Step 1: 2×2+3×3 = 4+9 = 13 // Sum of square of each digit
Step 2: 1×1+3×3 = 1+9 = 10
Step 3: 1×1+0x0 = 1 (A Happy Number)

We will see two approaches to find happy number in java.

Using Hashset

In this approach, we will use Hashset to tract the cycle and if sum=1 at the end of the cycle, then it is happy number.

Algorithm

  1. Take one variable sum for storing sum of square.
  2. Intialize a HashSet numbers, we will use this HashSet to track repeating cycle.
  3. Iteate through while loop until we get same number again and do following:
    1. Calculate the square of each digit present in the number and add it to the variable sum and divide the number by 10.
    2. Assign sum to number after each iteration
  4. If result sum is equal to 1, then the number is a Happy Number.
  5. Else the number is not happy Number.

Note: A number can not be a Happy Number if it makes a loop in its sequence. For example,

4x4 = 16

1x1+6x6 = 37

3x3+7x7 = 58

5x5+8x8 = 89

8x8+9x9 = 145

1x1+4x4+5x5 = 42

4x4+2x2 = 20

2x2+0x0 = 4 // Number itself

4 = 16  // Repeating process (loop), see step 1

Example

Here is complete example to find Happy number in java.

import java.util.HashSet;
import java.util.Set;

public class Main
{
    public static void main(String args[]) 
    {
        int number  = 1111111;
        int sum = 0;
        Set numbers = new HashSet();
        while(numbers.add(number)){     
            sum = 0;
            while(number>0) {
                sum += (number % 10)*(number % 10); 
                number /=10;
            }
            number = sum;
        }

        // if sum = 1, it is happy number 
        if(sum == 1) {
            System.out.println("It is a happy number");
        }else {
            System.out.println("It is not a happy number");
        }
    }
}

Output

It is a happy number

Using slow and fast pointers

In this approach, we will use slow and fast pointer to track the cycle.

Algorithm

  1. initialize two variables slow and fast with given number.
  2. Iterate through do while loop until we get a cycle (slow!=fast)
    1. Move slow pointer once by calling getSumOfSquareOfDigit() once.
    2. Move fast pointer twice by calling getSumOfSquareOfDigit() twice.
  3. If slow is equal to 1 at the end of cycle, it means it is happy number.

Example

Here is complete example to find Happy number in java.

package org.arpit.java2blog;

public class HappyNumberSlowFast {
    static int getSumOfSquareOfDigit(int num) {
        int ss = 0;
        while (num != 0) {
            ss += (num % 10) * (num % 10);
            num /= 10;
        }
        return ss;
    }

    // method return true if n is Happy number
    static boolean isHappynumber(int num) {
        int slow, fast;

        // initialize slow and fast by num
        slow = fast = num;
        do {
            // move slow number by one step
            slow = getSumOfSquareOfDigit(slow);

            // move fast number by two steps
            fast = getSumOfSquareOfDigit(getSumOfSquareOfDigit(fast));

        } while (slow != fast);

        // If slow and fast point meet and slow is equals to 1,
        // then it is happy number
        return (slow == 1);
    }

    // Main method
    public static void main(String[] args) {
        int n = 1111111;
        if (isHappynumber(n))
            System.out.println(n + " is a Happy number");
        else
            System.out.println(n + " is not a Happy number");
    }

}

Output

1111111 is a happy number

That’s all about How to find Happy Number in Java

]]>
https://java2blog.com/happy-number-program-java/feed/ 0