Home > Enterprise >  Java method to check if a given number is symmetric
Java method to check if a given number is symmetric

Time:04-11

iv made a method to check if a given number is symmetric or not.

-the method is based on the idea that the given number is an array .

-i gave the methood 4 deifferent parameters- numberLength , middle , point1,point2(both pointing at a certain digit in the number(as an array))

-although wrote the code correctly , and it works when im initializing a specific array , i dont know how to use the method for a given number .

How can i set this Method - with parameter (int number) , so i can chek on the given number.

Thank you A lot

CodePudding user response:

The easiest way to check if number symmetric or not is to map it to String::class, just like this:

// Your input number
Integer maybeSymmetricNumber = 12321;

String str = String.valueOf(maybeSymmetricNumber), reverseStr = "";

int strLength = str.length();

for (int i = (strLength - 1); i >=0; --i) {
  reverseStr = reverseStr   str.charAt(i);
}

if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
  System.out.println(str   " is a symmetric number.");
}
else {
  System.out.println(str   " is not a symmetric number.");
}

CodePudding user response:

This is probably the easiest. Just use remainder and division operators to reverse it and then compare to the original.

  • let d = 122, v = 0
  • v = v *10 d (d = 2)
  • d = d/10 (d = 12)
  • v = v * 10 d (d = 22)
  • d = d/10
  • v = v*10 d (d = 221) Thus not symmetrical
int[] data = {121, 12321,12322,223322, 98789, 22112, 1111,1212};

for (int d : data) {
    int v = 0;
    int k = d;
    while (k > 0) {
      v = v * 10   (k);
      k/=10;
    }
    System.out.printf("%-7d -> is%s symmetric.%n", d,  d == v ? "" : " not");
}

prints

121     -> is symmetric.
12321   -> is symmetric.
12322   -> is not symmetric.
223322  -> is symmetric.
98789   -> is symmetric.
22112   -> is not symmetric.
1111    -> is symmetric.
1212    -> is not symmetric.
  • Related