Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Create a function for encrypting which takes a cipher shift as parameter as well. Check if incoming character is letter. If is lower case encrypt it using ascii number:
to_char[ascii_of_char - asci_of_a + shift) % 26 + ascii_of_a]
.
Similar if letter is uppercase.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.*; public class CaesarCipher { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int length = stdin.nextInt(); String text = stdin.next(); int shift = stdin.nextInt(); for(int i = 0; i < length; i++) { char c = text.charAt(i); if(c >= 'a' && c <= 'z') { System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a')); } else if(c >= 'A' && c <= 'Z') { System.out.print((char)(((int)c - (int)'A' + shift) % 26 + (int)'A')); } else { System.out.print(c); } } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
'use strict'; const processData = input => { let lines = input.split('\n'); let text = lines[1]; let shift = parseInt(lines[2]); let encrypted = ''; for(let i = 0; i < text.length; i++) { if(text.charCodeAt(i) >= 'a'.charCodeAt(0) && text.charCodeAt(i) <= 'z'.charCodeAt(0)) { encrypted += String.fromCharCode((text.charCodeAt(i) - 'a'.charCodeAt(0) + shift) % 26 + 'a'.charCodeAt(0)) } else if(text.charCodeAt(i) >= 'A'.charCodeAt(0) && text.charCodeAt(i) <= 'Z'.charCodeAt(0)) { encrypted += String.fromCharCode((text.charCodeAt(i) - 'A'.charCodeAt(0) + shift) % 26 + 'A'.charCodeAt(0)) } else { encrypted += text.charAt(i); } } console.log(encrypted); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import scala.io.Source object CaesarCipher extends App { val lines = Source.stdin.getLines().toList val text = lines(1) val encryptionKey = lines(2).toInt val encrypted = text.map(caesarCipher(_, encryptionKey)) println(encrypted) def caesarCipher(c: Char, shift: Int): Char = { if(c >= 'a' && c <= 'z') { return ((c.toInt - 'a'.toInt + shift) % 26 + 'a'.toInt).toChar } if(c>= 'A' && c <= 'Z') { return ((c.toInt - 'A'.toInt + shift) % 26 + 'A'.toInt).toChar } return c } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
l = gets.to_i text = gets.to_s shift = gets.to_i text.each_codepoint do |c| if(c >= 'a'.ord && c <= 'z'.ord) print ((c - 'a'.ord + shift) % 26 + 'a'.ord).chr elsif (c >= 'A'.ord && c <= 'Z'.ord) print ((c - 'A'.ord + shift) % 26 + 'A'.ord).chr else print c.chr end end |