My teacher has asked us to create an int return method that will reverse a passed in int using only 3 lines, no strings and no use of the Math class and no loops within the method, also there can be no use of instance variables or other helper methods. Any clues on how to do this? My friends and I have yet to figure it out with those specific parameters.
Asked
Active
Viewed 91 times
-3
-
3"Reversing an int" - what does it mean? – Nir Alfasi Apr 05 '15 at 16:48
-
1I'm guessing if the input is 11110000, the result should be 00001111. – David W Apr 05 '15 at 16:49
-
This can be done in a single (very long) statement. – Oliver Charlesworth Apr 05 '15 at 16:52
-
like 123 should return 321 ?? – Prashant Apr 05 '15 at 16:58
-
If you want a "smartass" answer, then the same technique I'm using to check if a number is a palindrom here: http://stackoverflow.com/a/29228689/1057429 can be used to "reverse" a number, and it doesn't use any method from the String-library only StringBuilder so technically it might be a valid answer. – Nir Alfasi Apr 05 '15 at 17:13
-
Jonny Jonny - Yes Papa! Doing homework? - Yes Papa! Asking S O ? No Papa! Let me google... Ha ha ha! – Abhay Apr 06 '15 at 05:08
2 Answers
0
Try this... The method reverseDigits() recursively call itself, No Strings,No Math Lib,No Loops ,, But Recursion is there..
public class Test {
static int rev_num = 0, base_pos = 1;
public static int reverseDigits(int i){
if(i > 0)
{
reverseDigits(i/10);
rev_num += (i%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}
public static void main(String[] args) {
System.out.println(Test.reverseDigits(123));
}
}

AsSiDe
- 1,826
- 2
- 15
- 24
0
This seems to work for all integer inputs for which overflow does not occur. Note the use of variable length argument lists, used to pass extra information down the chain of recursive functions.
public class Reverse {
public static int reverse(int... n) {
if (n.length == 1) return reverse(n[0]/10,n[0]%10);
else if (n[0] == 0) return n[1];
else return reverse(n[0]/10,10*n[1]+n[0]%10);
}
public static void main(String[] args) {
System.out.println(reverse(Integer.parseInt(args[0])));
}
}

Edward Doolittle
- 4,002
- 2
- 14
- 27