Created
April 30, 2018 02:16
-
-
Save julianbonilla/286c9006a1f85e478f28cd840dd7235f to your computer and use it in GitHub Desktop.
Reverse and Add Palindrom - https://www.geeksforgeeks.org/reverse-and-add-function/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* Reverse the digits in a number *) | |
fun reverse_num(num : int) = | |
Int.fromString( implode (rev (explode (Int.toString(num)))) ) | |
(* Test if a string is a palindrome ie. 'abba' *) | |
fun palindrome (str : string) = | |
let val str_list = explode str | |
in | |
str_list = rev str_list | |
end | |
(* The reverse and add function starts with a number, reverses its digits, and | |
adds the reverse to the original. If the sum is not a palindrome (meaning it | |
does not give the same number read from left to right and right to left), we | |
repeat this procedure until it does. For example, if we start with 195 as the | |
initial number, we get 9,339 as the resulting palindrome after the fourth | |
addition *) | |
fun reverse_and_add (num : int) = | |
let val reverse_num = reverse_num(num) | |
val sum = valOf reverse_num + num | |
val str_sum = Int.toString(sum) | |
in | |
if num > valOf Int.maxInt (* max int is 1073741823 *) | |
then "No palindrome exists" | |
else if palindrome(str_sum) | |
then str_num | |
else reverse_and_add(sum) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment