-
Integers - Position
I have an integer called "numb" which has the value of 155.
Is there a way to split the integer up like you can with strings? With strings you can have substrings. Can I do the same thing with an integer? I need to write a recursive method that writes the value backwords. Any help you can offer is appreciated.
Thanks.
-
If you have a string reversing function already, you can convert a number to a string by simply appending an empty string, ie...
Code:
String s = 155 + ""; // s = "155"
:)
-
or:
Code:
String s = Integer.toString (numb);
and then proceed as before
-
Well you could cheat and use StringBuffer
Code:
public class TestString{
public static void main(String args[]){
StringBuffer buf = new StringBuffer("Beres");
System.out.println(buf.reverse());
}
}
-
or you could also just write one yourself
Code:
public String reverseRecurse(String inStr) {
String outStr = new String();
if (inStr.length() > 0 ) {
outStr = inStr.charAt(inStr.length()-1) + reverseRecurse (inStr.substring(0, inStr.length()-1));
}
return output;
}
i dont have java at work to test this but I think it should work beautifully.
-
also, you may want to do this mathematically. It should have better performance for you. This could be done by taking the modulus of the number and using division, but I will let you think of this one, hate to have the teacher think you know everything :)
bill