Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 8 of 8
Thread: Recursion help

03252011, 12:33 AM #1
 Join Date
 Mar 2011
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Recursion help
Got this problem I have been struggling on for hours that is extra credit for my class:
Write a recursive method that returns the currency format of the given integer value (val ). All intermediate operations must be carried out as integer arithmetic. The only time you are allowed to use string operations is to return the result. You may use the String.valueOf() or Long.toString() methods. Recall that 27341 % 1000 is 341 and 27341 / 1000 is 24.
public String formatAsCurrency(long val) { }
For this question, make sure your method works correctly for numbers that are multiple of 1000 or has consecutive zeros. Examples:
formatAsCurrency(5000481L) returns "5,000,481"
formatAsCurrency(434L) returns "434"
formatAsCurrency(76L) returns "76"

03252011, 01:33 AM #2
 Join Date
 Dec 2007
 Posts
 6,682
 Thanks
 436
 Thanked 890 Times in 879 Posts

Users who have thanked oesxyl for this post:
wolveine903 (03252011)

03252011, 02:29 AM #3
 Join Date
 Mar 2011
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Thanks, it got me started but still stuck, hopefully i can get some credit. Its an upcoming topic in my class and is extra credit on homework since we haven't really learned it yet.

03252011, 02:39 AM #4
 Join Date
 Dec 2007
 Posts
 6,682
 Thanks
 436
 Thanked 890 Times in 879 Posts

03252011, 03:01 AM #5
 Join Date
 Mar 2011
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
I know some what how Recursive writing works for Java. I know that first is the base case, but then i get confused to how to set up the recursive call(s) after that.

03252011, 03:19 AM #6
 Join Date
 Dec 2007
 Posts
 6,682
 Thanks
 436
 Thanked 890 Times in 879 Posts
when you call formatAsCurrency(5000481L) and you implement what i said, first step will be to check if val is less then 1000L.
obvious in this case the test will fail then you will return the result of concatenation between the result of calling formatAsCurrency(5000L) with a comma, ",", and the rest 481L.
formatAsCurrency(5000L) will do same thing because 5000L > 1000L but this time will call formatAsCurrency(5L) wich will return '5' a string because is less then 1000L.
so after each return and concatenation will have 5,000,481
Edit:
Code:return formatAsCurrency(5000481L)  \ return formatAsCurrency(5000L) + "," + "481";  \ return formatAsCurrency(5L) + "," + "000";  \ return "5";
best regardsLast edited by oesxyl; 03252011 at 03:28 AM.

03252011, 03:24 AM #7
 Join Date
 Mar 2011
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
Ok now can you write it out for me?

03252011, 03:32 AM #8
 Join Date
 Dec 2007
 Posts
 6,682
 Thanks
 436
 Thanked 890 Times in 879 Posts