Reverse a number and number operations in java

     Number is a basic element in mathematics. Operations on numbers are reverse a number, counting the number of digits and sum of the digits.

Let us code the operations.

Reverse a number:

              Reverse a number is reversing the digits in the number. Logic behind the program is given below…

  • ·       First, read the number as input.
  • ·       Using a while loop, repeat the process.
  • ·       Split the last digit separately by using mod function.
  • ·       Multiply the number with its position.
  • ·       Repeat the process until the last digit.
  • ·       Print the reversed number.

#Java Program to reverse a number

class Revnumber

{

 public static void main(String args[])

 {

  int n =134,re=0,a=0;

  System.out.println("The number is :"+n);

  while(n>0)

  {

   a=n%10;

   re=re*10+a;

   n=n/10;

  }

  System.out.println("The reverse number is:"+re);

 }

}

Here, is the output.


Counting the number of digits:

              This program counts the number of digits in the given number. The logic behind the program is..

  • ·       Get the number.
  • ·       Check the number is greater than zero, repeat the process.
  • ·       Split the last digit by mod function.
  • ·       Increase the count.
  • ·       Divide the number by 10.
  • ·       Repeat the process.
  • ·       Finally, print the counting value.

#Java Program to count the number of digits in the number

class CountNumber

{

 public static void main(String args[])

 {

  int n =134,c=0,a=0;

  System.out.println("The number is :"+n);

  while(n>0)

  {

   a=n%10;

   c = c+1;

   n=n/10;

  }

  System.out.println("The Number of the digits are:"+c);

 }

}

When executing this program,you get the below output.

3.Sum of the digits in number:

              This program splits each digit, adds the digits to sum value.

class SumNumber

{

 public static void main(String args[])

 {

  int n =134,s=0,a=0;

  System.out.println("The number is :"+n);

  while(n>0)

  {

   a=n%10;

   s= s+a;

   n=n/10;

  }

  System.out.println("The sum of the digits are:"+s);

 }

}

The output is:

These are java programs on numbers. Keep Coding!!!!!



No comments:

Post a Comment