You are here:

Advertisement

I was given this question:"A number is said to be a step number if for each pair of consecutive digits in the no. the difference is 1 (eg:456567). Single digit numbers can be considered as step numbers."

Here's the code I've written:

import java.util.*;

public class question2 {

public static void main(String[] args){

Scanner s = new Scanner(System.in);

System.out.print("Input Nmber:");

int x = s.nextInt();

String y = s.nextLine();

int a = y.length();

int r1 = 0;

int r2 = 0;

int z = 0;

int c = 0;

int i = 0;

while(i>a){

r1 = x%10;

r2 = ((x%100)-r1)/10;

c = r1-r2;

if (c != 1){

z = 1;

}

x = x/10;

i = i+1;

}

if(z==0){

System.out.print("step");

}

else{

System.out.print("not step");

}

}

}

the problem is that the code ALWAYS gives me "step" even if the no. is not!! and I don't know why is that!!!

I really need a very quick reply! Thank You in advance.

Hello,

Sorry, I am abit late on this. Been busy with other things.

suppose, the user enters a number(456567) now, you do know for it to be a step number, you have to be sure that 4-5==5-6==6-5==5-6==6-7 ={1} absolute value of 1 right?

If that is what your programme should do, then

1. get the number

2. run a for loop on each digit in the number set

3. find the difference between the present digit and the digit next

4. if the difference is either 1 or -1

5. Then it is a step number

6. else

i.e if during the loop you find a single difference that is not 1 or -1 the whole set has been contaminated by that single

difference, you have to conclusively conclude it is not a step number..

Now, apply this concept to your code and am sure it will work fine :) sorry for the late reply.

- Add to this Answer
- Ask a Question

Rating(1-10) | Knowledgeability = 10 | Clarity of Response = 10 | Politeness = 10 |

Comment | No Comment |

Java

Answers by Expert:

I can confidently answer questions relating to JSE and JEE6 . Please no questions on JME.

I am experienced in JSE and JEE6
**Education/Credentials**

I am a BSEng graduate