Once I was asked (as a challenge) to write an algorithm that finds numbers that, rotated 180 degrees, look exactly the same (strobogrammatic numbers). For some reason, that 'challenge' came up during a conversation I recently had with a co-worker, so I took some time to come up with a solution (in Java):
/**
* by: Rei Colina
* A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
*
* To compile run: javac Strobogrammatic.java
* To run the test use: java Strobogrammatic
*/
class Strobogrammatic {
public static void main(String args[]) {
System.out.println("Count is: " + strobogrammaticCounter(0,1010));
}
/**
* Counts the amount of strobogrammatic numbers that exist in a given range.
* It also prints all the strobogrammatic numbers found in that range
*/
public static int strobogrammaticCounter(long low, long high) {
int count = 0;
String number = "";
for (long i = low; i <= high; i++) {
number = Long.toString(i);
if (!(number.contains("2") || number.contains("3") || number.contains("4") || number.contains("5") || number.contains("7"))) {
if (i == reverseNumber(i)) {
System.out.println(i);
count ++;
}
}
}
return count;
}
private static char rotateSixOrNine(char number) {
switch (number) {
case '6':
return '9';
case '9':
return '6';
default:
return number;
}
}
private static long reverseNumber(long number) {
//convert to string so we can operate on each digit
String numberString = Long.toString(number);
//reverse
numberString = new StringBuilder(numberString).reverse().toString();
//operate on each 'digit' by applying rotateSixOrNine to each char
String newNumber = "";
for (int i = 0; i < numberString.length(); i++){
char digit = numberString.charAt(i);
newNumber = newNumber + rotateSixOrNine(digit);
}
return Long.parseLong(newNumber);
}
}