73352

Java recursion and integer double digit

Question:

I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.

For example doubleDigit(3487) would return 33448877.

I'm stuck because I can't figure out how I would read each number in the digit I guess.

Answer1:

To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.

String doubleDigit(Integer digit) { if (digit == 0) { return ""; } else { Integer thisDigit = digit % 10; Integer remainingDigits = (digit - thisDigit) / 10; return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString(); } }

Answer2:

If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):

long doubleDigit(long amt) { if (amt == 0) return 0; return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10; }

The function is of course limited by the <a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="nofollow">maximum size of a long</a> in Java.

Answer3:

I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).

public static int doubleDigits(int n) { if (n == 0) { return 0; } else { int lastDigit = n % 10; return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit; }

Answer4:

There's no need to use recursion here.

I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):

int number = 3487; int output = 0; int shift = 1; while (number > 0) { int digit = number % 10; // get the least-significant digit output += ((digit*10) + digit) * shift; // double it, shift it, add it to output number /= 10; // move to the next digit shift *= 100; // increase the amount we shift by two digits }

This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)

<strong>Edit:</strong> Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)

private static long DoubleDigit(long input) { if (input == 0) return 0; // don't recurse forever! long digit = input % 10; // extract right-most digit long doubled = (digit * 10) + digit; // "double" it long remaining = input / 10; // extract the other digits return doubled + 100*DoubleDigit(remaining); // recurse to get the result }

Note I switched to long so it works with a few more digits.

Answer5:

You could get the String.valueOf(doubleDigit) representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.

If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do Integer.valueOf(yourString) or something like that.

Recommend

  • Best way to read/parse a untyped binary file in Delphi
  • Get Wages Yearly Increment Column Wise Using Sql
  • Two Datatables in One Page
  • How to integrate dynamically JS code in success page in magento
  • cannot run python script file using windows prompt
  • Group By and add columns
  • Ruby: Invert a hash to also preserve non unique values
  • Thread Synchronization with IntentService
  • AWS S3 implementation for serving private files
  • const char **a = {“string1”,“string2”} and pointer arithametic
  • Gradle - How to detect --debug flag from command line?
  • Getting proper map boundaries
  • why 0.1+0.2-0.3= 5.5511151231258E-17 in php [duplicate]
  • Show records ordered with maximum price first in PHP & MySQL
  • segue from landscape only to portrait only
  • Hiding Directories Programatically in C#
  • Smack 4.1.0 android Roster not displaying
  • Send data from edittext to listview
  • Retrofit SocketTimeoutException (and/or http 500 error) on http-POST
  • Unable to connect to OnVif enabled camera using C#
  • Extract All Possible Paths from Expression-Tree and evaluate them to hold TRUE
  • Retrieve IP address of device
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • how to avoid repetitive constructor in children
  • xtable package: Skipping some rows in the output
  • Spark fat jar to run multiple versions on YARN
  • What is Eclipse's Declaration View used for?
  • Volley JsonObjectRequest send headers in GET Request
  • Window Size for Mac application
  • Javascript convert timezone issue
  • ActionScript 2 vs ActionScript 3 performance
  • WOWZA + RTMP + HTML5 Playback?
  • json Serialization in asp
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • Binding checkboxes to object values in AngularJs
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?