One of the oldest codes moves every letter along the alphabet.
What to build
A program that encrypts text by shifting each letter by a fixed number of places.
Requirements
- Read the shift k on the first line (it may be negative), and one line of text on the second.
- Shift every English letter by k places, wrapping from z to a; keep upper and lower case. Leave all other characters unchanged.
- Print the new text on the first line and
shifted: Non the second line, where N is how many letters were shifted.
Input
Line 1: k. Line 2: a line of text.
Output
Two lines.
Constraints
-1000 ≤ k ≤ 1000; the text has at most 100 characters.
Example
Input:
3
Hello, World!
Output:
Khoor, Zruog!
shifted: 10
Why it works
A letter is a number: subtracting 'a' gives its place from 0 to 25, adding the shift and taking % 26 wraps around, and adding 'a' gives the letter back. The first reduction of k makes negative shifts work too.
Examples
Example 1 · Input
3 Hello, World!
Expected output
Khoor, Zruog! shifted: 10
Example 2 · Input
-3 Khoor, Zruog!
Expected output
Hello, World! shifted: 10
Hints
Hint 1
Convert the line to runes with []rune(line) and change only the letters 'a' to 'z' and 'A' to 'Z'.
Hint 2
Use shift = ((k % 26) + 26) % 26 so a negative shift works, then rotate with (r - 'a' + shift) % 26 + 'a'.
Solution
Show one correct solution (try it yourself first)
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
k, _ := strconv.Atoi(strings.TrimSpace(scanner.Text()))
scanner.Scan()
line := scanner.Text()
shift := ((k % 26) + 26) % 26
out := []rune{}
count := 0
for _, r := range line {
switch {
case r >= 'a' && r <= 'z':
out = append(out, (r-'a'+rune(shift))%26+'a')
count++
case r >= 'A' && r <= 'Z':
out = append(out, (r-'A'+rune(shift))%26+'A')
count++
default:
out = append(out, r)
}
}
fmt.Println(string(out))
fmt.Printf("shifted: %d\n", count)
}