Skip to content

Instantly share code, notes, and snippets.

@gabidavila
Last active April 11, 2019 17:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabidavila/d5d461d26a3445ab8f43405f8f9c276a to your computer and use it in GitHub Desktop.
Save gabidavila/d5d461d26a3445ab8f43405f8f9c276a to your computer and use it in GitHub Desktop.
Determines if a positive integer is a palindrome mathematically

Using Math to find palindromes

For an instance, forget that arrays and strings exists. Your challenge, is to say if a number is a palindrome or not using mostly mathematical approach.

The string you will receive (because it is an user input), it always positive. You can assume that every 0 <= n < 10 is a palindrome.

function numberOrder(n = 0) {
if (n == 0) {
return 1;
}
return Math.floor(Math.log10(n));
}
function isPalindrome(n, leftPadZero = false) {
if (n < 10 && n >= 0) {
return true;
} else if (n < 0) {
return false;
}
const order = numberOrder(n);
const exp = Math.pow(10, order);
const firstNumber = !leftPadZero ? Math.floor(n/exp) : 0;
const lastNumber = n % 10;
if (firstNumber != lastNumber) {
return false;
}
const remainder = Math.floor((n % exp) / 10);
if (order - numberOrder(remainder) != 2) {
leftPadZero = true;
}
if (remainder == 0) {
return true;
}
return isPalindrome(remainder, leftPadZero);
}
import math
def number_order(n):
return math.floor(math.log10(n))
def is_palindrome(n, left_zero = False):
number_int = int(n)
if number_int >= 0 and number_int < 10:
return True
elif number_int < 0:
return False
size_n = len(str(n))
size_int_n = len(str(number_int))
left_zero = size_n != size_int_n
order = number_order(number_int)
divider = int(math.pow(10, order))
last_digit = number_int % 10
if left_zero:
first_digit = 0
else:
first_digit = math.floor(number_int / divider)
if first_digit != last_digit:
return False
remainder = int((number_int - first_digit * divider - last_digit)/10)
return is_palindrome(remainder, left_zero)
def number_order(number)
return Math.log10(number).floor unless number == 0
1
end
def is_palindrome?(number, left_pad_zero = false)
return false if number < 0
return true if number < 10
order = number_order(number)
exp = 10 ** order
first_number = (number/exp).floor
first_number = 0 if left_pad_zero
last_number = number % 10
return false unless first_number == last_number
remainder = ((number % exp)/10).floor
left_zero = true unless order - number_order(remainder) == 2
if remainder == 0
true
else
is_palindrome?(remainder, left_zero)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment