-3

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.

Hypnova
  • 25
  • 2

2 Answers2

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