# Find the closest palindromic number

## Pyth, ~~26~~ 20

```
Lnb_bWP`+QZ=Z-g0ZZ)Z
```

Updated to meet the new rules.

The program runs in an infinite loop which tests every possible increment, in the order 0, -1, 1, -2, -2 ...

Explanation:

```
Q=eval(input()) implicit
Z=0 implicit
Lnb_b def P(b): return b != rev(b)
WP`+QZ while P(repr(Q+Z)):
=Z-g0ZZ Z=(0>=Z)-Z
) <end while>
Z print(Z)
```

Example run:

```
python3 pyth.py programs/palin.pyth <<< 965376457643450
-2969881
```

This took 23 seconds.

Bonus solution, same character count:

```
Wn`+QZ_`+QZ=Z-g0ZZ)Z
```

## Ruby, ~~111~~ 84 bytes

```
i=$*[j=-1].to_i
r=->j{s=(i+j).to_s
abort(j.to_s)if s==s.reverse}
loop{r[j+=1]
r[-j]}
```

Takes the number as its only command-line argument.

## CJam, ~~34~~ ~~29~~ 25 bytes

```
q~:I!{:R1<R-RI+`_W%=!}g;R
```

Try it online.

### Examples

```
$ cjam palfind.cjam <<< 120; echo
1
$ cjam palfind.cjam <<< 121; echo
0
$ cjam palfind.cjam <<< 122; echo
-1
```

### How it works

```
q~:I " Read from STDIN, evaluate and save the result in “I”. ";
! " Compute the logical NOT (0 since the integer is positive). ";
{ " ";
:R " Save the topmost integer in “R”. ";
1<R- " Compute (R < 1) - R. This produces the sequence 0 → 1 → -1 → 2 → -2 → … . ";
RI+ " Push I + R. ";
`_ " Cast to string and push a copy. ";
W%=! " Check if the reversed copy matches the original. ";
}g " If it doesn't, repeat the loop. ";
;R " Discard the integer on the stack and push “R”. ";
```