Hello. I'm currently a 10th grader who's been sitting in front of the computer for hours trying to figure this assignment out. First, my teacher gave me a reverse integer problem. He wants us to reverse the numbers 12345, 10001, 1200, and 5, and display in in the output. The leading zeros can be omitted. I got the method down here (for the first integer):

    //initialize
    int tmpInt1 = 0;

    while(tmpInt1 == 12345) 
    {
        newInt *= 10;
        newInt += tmpInt1 % 10;
        tmpInt1 /= 10;
    }

However, there seems to be a problem displaying it in the output, which looks like this:

    FunLoops fun = new FunLoops();
    System.out.println("12345 reversed ---> " + fun.reverse(12345));

That's just the first reverse integer, and I am clueless on how to add the other numbers in. Should I use a nested loop? If so, how should I use it? After I figure this out, I still need to do the LCM and the Magic Square part, which is even more complicated. I'm glad I have a 4-day weekend, so this isn't that urgent. But I still need the help. Can someone please show me the correct way to do this? Thank you all so much!!!

Dani AI

Generated

A few concise, practical additions that fill gaps in the existing replies:

The loop bug in 's first post comes from testing equality to the original value instead of looping until the working value is exhausted. 's idea of a single, general reverse routine is the right pattern — call it for each test value (no nested loops needed). Important edge cases: negative numbers (preserve the sign separately), input 0 (should produce 0), and Integer.MIN_VALUE (Math.abs(Integer.MIN_VALUE) overflows). For inputs larger than 32-bit range consider long or BigInteger. Arithmetic reversal naturally drops leading zeros (so 1200 -> 21), which matches the assignment requirement.

A robust gcd + lcm approach avoids brute force and reduces overflow risk. Example (Java):

public static int gcd(int a, int b) {
  a = Math.abs(a); b = Math.abs(b);
  while (b != 0) {
    int t = a % b;
    a = b;
    b = t;
  }
  return a;
}

public static long lcm(int a, int b) {
  if (a == 0 || b == 0) return 0L;       // convention used here
  int g = gcd(a, b);
  return Math.abs((long)a / g * b);      // divide first to avoid a*b overflow
}

Magic-square notes (what to check and how to build odd-order squares). To verify a candidate n×n magic square: confirm it contains each integer 1..n^2 exactly once, compute the target sum (n(nn + 1)/2), and check every row, every column, and both main diagonals equal that target. To construct an odd-order magic square use the Siamese (de la Loubère) method: start at middle of top row with 1, then for k=2..n*n move up one row and right one column (wrap around); if the target cell is occupied, move down one from the last placed cell and continue.

Small practical tips: 's string-based reversal works but StringBuilder + Integer.toString (or String.valueOf) is preferable in single-threaded code. Add unit tests for the listed inputs plus edge cases (0, negatives, very large values) and prefer the divide-first lcm formula to avoid silent overflow.

Recommended Answers

All 6 Replies

>I got the method down here (for the first integer):
Why not write it generally for all integers?

public int reverse_integer ( int val )
{
  int ret = 0;

  while ( val != 0 ) {
    ret = 10 * ret + ( val % 10 );
    val /= 10;
  }

  return ret;
}

>I am clueless on how to add the other numbers in.
It's easiest just to call reverse for each number, provided that reverse can handle any integer intelligently:

System.out.println("12345 reversed ---> " + fun.reverse(12345));
System.out.println("12345 reversed ---> " + fun.reverse(10001));
System.out.println("12345 reversed ---> " + fun.reverse(1200));
System.out.println("12345 reversed ---> " + fun.reverse(5));

Thank you, Narue! This portion of the program is working now! :)

Hopefully, I'm not asking too much, but there's just one last thing I need, and that is how to figure out the LCM of two numbers. I don't really know how to approach it. Should it be best if I stick with using a while loop, compare the two integers, and increment it until it finds the LCM, or should I do something else?

Calculating the least common multiple is trivial if you have a routine to find the greatest common divisor:

public int lcm ( int a, int b )
{
  return a * b / gcd ( a, b );
}

You shouldn't have any trouble finding out the algorithm for finding the greatest common divisor, it's everywhere. :)

Thank you so much Narue! You're the best!! :cool:

class ReverseTest {

public static void main(String[] args) {

int originalInt = 12345;
int reversedInt = 0;

// convert Integer value to String. Strings can be easily reversed
String intToString = new Integer(originalInt).toString();

//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(intToString);

//Reverse the contents of the StringBuffer
buffer = buffer.reverse();

// convert String back to integer
reversedInt = Integer.parseInt(buffer.toString());


// print out the result
System.out.println("Reversed Integer: " + reversedInt);

} // main

}

I bet the OP has been waiting impatiently for the 7 1/2 years since he posted and then solved this problem, just in case you would come along with another solution. That's great. He can hand his homework in now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.