I have the following problem:
The stepping number:
A number is called a stepping number if every adjacent digits, except those separated by commas, differ by 1. A stepping number can't be a 1-digit number, it must be at least a 2-digit number. For example, 45 and 8,343,545 are stepping numbers. But, 890,098 is not. The difference between ‘9’ and ‘0’ should not be considered as 1.
Given start number s and an end number e your function should list out all the stepping numbers in the range including both the numbers s & e.
My Attempt:
public void steppingNumber(int s, int e) {
while(s <= e) {
String str = String.valueOf(s);
if(isSteppingNumber(str)) System.out.print(str + " ");
s++;
}
}
public boolean isSteppingNumber(String str) {
if(str.length() == 1) return false; // 1-digit number can't be a stepping number
List<String> numbers = new ArrayList<>();
while(str.length() >= 3) { // get every 3-digit comma-separated number
numbers.add(str.substring(str.length()-3));
str = str.substring(0,str.length()-3);
}
numbers.add(str); // Also get the last number left
for(String num : numbers) { // for every 3-digit comma-separated number, check if it's a stepping number
for(int i = 1; i < num.length(); i++) {
int previousDigit = Character.getNumericValue(num.charAt(i-1));
int currentDigit = Character.getNumericValue(num.charAt(i));
if(Math.abs(previousDigit - currentDigit) != 1) return false;
}
}
return true;
}
If the question were only to check if a number was a stepping number, I think my solution would be fine. However, if I should list all stepping numbers within the range, say 1 to 10^15, then my solution will run linear time, leave alone the checking part. Can anyone give a better solution for the given problem?
String str = Integer.parseInt(s);
" :( Can you please provide the correct, working code here? Anyways, for starters, why is the method performing onString
s when a primitiveint
/long
value should suffice? Especially when the comma is 'only used for explanation purposes'. In that case, there is also no need for splitting the input into three digits. That's the slightly confusing part... \$\endgroup\$Integer.toString()
method, or the more complexjava.text.NumberFormat
classes? \$\endgroup\$String.valueOf(s)
. I converted int to String because I wanted to access every digit, of a given number, at constant time. For example, if I had integer345
, I wouldn't be able to access 3, 4, or, 5 directly. Another way of doing this is using int array, so I can directly point tonum[0]
,num[1]
, ornum[2]
. I hope that makes sense. \$\endgroup\$