01.The Mirror Gate

EasyMath
Pattern lockedSolve it, or make 3 submissions, to unlock which classic problem this story hides.
Night view of a hill fort with domed towers. A stone mirror above the gate shows the token number 121. Below it, the mirror shows the same digits written from right to left. A guard with a lantern stands near the road.

// The story

There is an old fort on a hill above the village of Chandragiri. Its gate is special. Long ago, the king's engineer Meera Bai built this gate. It stops travellers who carry fake tokens.

Every token has a number on it. A traveller holds up the token. A shiny stone mirror on the gate shows the number written from right to left. The gate opens only if the mirror shows exactly the same number. Every digit and sign must be in the same place.

Ravi is the night guard. He checks thousands of tokens every night, and his eyes are tired. Write a program that does this check for him.

// Your task

You are given the number x on a token. Return true if the Mirror Gate opens for it. Otherwise, return false.

The rules of the gate:

  • The mirror writes all the symbols of x from right to left. This includes the minus sign.
  • The gate opens only if the mirror shows exactly the same symbols as the token.
  • A token with one digit (like 0 or 7) always opens the gate.

Input: one integer x. Limits: -231 ≤ x ≤ 231 − 1.

Example 1:

Input:
121

Output:
true

The mirror shows 121. This is the same as the token, so the gate opens.

Example 2:

Input:
-121

Output:
false

The mirror shows 121-. The minus sign is now at the other end, so the gate stays shut.

Example 3:

Input:
10

Output:
false

The mirror shows 01. This is not the same as 10, so the gate stays shut.

// Constraints

  • -2^31 <= x <= 2^31 - 1

Time limit: 5s ·  Memory limit: 256 MB

Hint 1

A token with a minus sign never opens the gate. In the mirror, the sign moves to the other end.

Hint 2

Build the mirror number yourself, one digit at a time. Then compare it with the number on the token.

Hint 3

Can you build the mirror number using only % 10 and / 10? Try it without changing the number into a string.

Solution.java
Sample tests