Added functions to check for palindromes and convert nums to bin strings

This commit is contained in:
2021-06-29 14:14:35 -04:00
parent a9de121a88
commit 75f4441f18
2 changed files with 115 additions and 2 deletions

View File

@@ -1,7 +1,7 @@
--luaClasses/Algorithms.lua
--Matthew Ellison
-- Created: 02-04-19
--Modified: 06-01-21
--Modified: 06-29-21
--This is a file of algorithms that I have found it useful to keep around at all times
--[[
Copyright (C) 2021 Matthew Ellison
@@ -361,3 +361,33 @@ function factorial(num)
end
return fact;
end
--Returns true if the string passed in is a palindrome
function isPalindrome(str)
local rev = string.reverse(str);
if(str == rev) then
return true;
else
return false;
end
end
--Converts a number to its binary equivalent
function toBin(num)
--Convert the number to a binary string
local binNum = "";
while(num > 0) do
local rest = math.fmod(num, 2);
if(rest == 1) then
binNum = binNum .. "1";
else
binNum = binNum .. "0";
end
num = (num - rest) / 2;
end
binNum = string.reverse(binNum);
if(binNum == "") then
binNum = "0";
end
return binNum;
end