Created
April 16, 2020 06:11
-
-
Save atonamy/9ec85a254522a9cb2810e280b51df512 to your computer and use it in GitHub Desktop.
Technical test for Igloohome
This file contains hidden or 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
fun CaesarCipher(str: String, num: Int): String { | |
val result = StringBuilder() | |
for(i in str.indices) { | |
if(str[i].toLowerCase() in 'a'..'z') { | |
val a = 'a'.toLong() | |
val A = 'A'.toLong() | |
val shift = (str[i] + num).toLong() | |
val letterLower = shift - a | |
val letterUpper = shift - A | |
val lower = ('z' + 1).toLong() - a | |
val upper = ('Z' + 1).toLong() - A | |
when { | |
str[i].isLowerCase() && shift < a -> { | |
val position = (letterLower % lower) | |
result.append((if(position < 0) lower + position + a else position + a).toChar()) | |
} | |
str[i].isUpperCase() && shift < a -> { | |
val position = (letterUpper % upper) | |
result.append((if(position < 0) upper + position + A else position + A).toChar()) | |
} | |
str[i].isLowerCase() -> result.append(((letterLower % lower) + a).toChar()) | |
str[i].isUpperCase() -> result.append(((letterUpper % upper) + A).toChar()) | |
else -> result.append(str[i]) | |
} | |
} | |
else result.append(str[i]) | |
} | |
return result.toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment