Stepping Number

In this program we are given with an long integer, if difference of adjacent digit is 1, then it is a stepping number else return -1
import java.util.*;
public class HackerRank {
public static int steppingNumber(int input1)
{
//Write code here
int result=0;
int i=0,remainder=0;
String num=String.valueOf(input1);
int [] arr=new int [num.length()];
while(input1>0){ //converting integer to integer array
remainder=input1%10;
arr[i]=remainder;
input1=input1/10;
i++;
}
int f=0,g=1,x,y;
do{
x=arr[f];
y=arr[g];
if((x-y)==1||(y-x)==1){ //to find whether is stepping number or not
result=1;
f++;
g++;
}
else {
result=-1;
break;
}
}while(g<arr.length);
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int output = 0;
int ip1 = Integer.parseInt(in.nextLine().trim());
output = steppingNumber(ip1);
System.out.println(String.valueOf(output));
in.close();
}
}
view raw SteppingNumbers hosted with ❤ by GitHub




Input: 123

Output: 1

Input: 890

Output: -1

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series