Categories

# Display Alternate Digits of an Integer

Write a program in Java to allow the user to enter a positive integer.

Now form another integer by using the alternate digits of the given integer.

Example:
INPUT:
N = 4532
OUTPUT:
43

``````import java.io.*;
class Alternate{
public static void main(String args[])throws IOException{
System.out.print("N = ");
String s = Integer.toString(n);
String alt = "";
for(int i = 0; i < s.length(); i += 2)
alt += s.charAt(i);
int result = Integer.parseInt(alt);
System.out.println("Required Number: " + result);
}
}``````

## 4 replies on “Display Alternate Digits of an Integer”

sayan ranasays:

Sir,can we use Math.abs() to convert the integer to a positive integer in the above program?

Yes!

sayan ranasays:

Sir,can we use this procedure to create a new number by all the alternate digits of the original number?
import java.util.Scanner;
class AlternateDigits{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“N = “);
int n = sc.nextInt();
int n2=0,p=0;boolean flag=false;
for(int i=n;i!=0;i/=10)
{
int dg=i%10;
if(flag==true)
{ n2+=dg*(int)Math.pow(10,p);
p++;
flag=false;
}
else
flag=true;
}
System.out.println(“New number:”+n2);
}}

Yes!

This site uses Akismet to reduce spam. Learn how your comment data is processed.