Hi,
Although I figured it out with the simple logic of how many digits are in a specific number range.
I initially thought that we could solve this by dividing the stream by 10 and storing it in a variable which should represent the amount of digits, we should then be able to use this to check the conditions. I had a quick go and I can't get my initial program to run correctly although it will compile so I'm guessing theres some logical problem. Does anybody know if this is a good way to go about this or how I can make use of this? It seemed that taking the route of the number range seemed a bit easy and I'm trying to think of other ways I can tackle such problem.
Just an idea :)
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Number: ");
int a = Integer.parseInt(myBufferedReader.readLine());
int counter = 0;
while (a > 0){
int b = a/10;
counter++;
}
if ((a%2 ==0)&&(counter==1)){
System.out.println("even single-digit number");
}
else if ((a%2 == 1) && (counter==1)){
System.out.println("odd single-digit number");
}
else if ((a%2==0)&&(counter==2)){
System.out.println("even two-digit number");
}
else if ((a%2==1)&&(counter==2)){
System.out.println("odd two-digit number");
}
else if ((a%2==0)&&(counter==3)){
System.out.println("even three-digit number");
}
else if ((a%2==1)&&counter==3)){
System.out.println("odd three-digit number");
else {
}
}
}
}
sean
Level 8
Alternative idea
Archived
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
1 April 2019, 13:23useful
in the above code that while loop is infinite because the condition of it continuing is that a is greater than 0, but nothing is done to modify a in the loop. Change the line directly following this from 'int b = a/10;' to 'a = a/10;' and it should work. You can definitely clean up that huge block of if-else code with some simple changes:
+1