mirror of
https://bitbucket.org/Mattrixwv/luaclasses.git
synced 2025-12-06 18:33:59 -05:00
Added functions to check for palindromes and convert nums to bin strings
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user