One simple way to encrypt a string is to “rotate” every alphanumeric character by a certain amount. Rotating a character means replacing it with another character that is a certain number of steps away in normal alphabetic or numerical order. For example, if the string “Zebra-493?” is rotated 3 places, the resulting string is “Cheud-726?”. Every alphabetic character is replaced with the character 3 letters higher (wrapping around from Z to A), and every numeric character replaced with the character 3 digits higher (wrapping around from 9 to 0). Note that the non-alphanumeric characters remain unchanged. Given a string and a rotation factor, return an encrypted string.


Test Cases

Example 1:

input = Zebra-493?
rotationFactor = 3
output = Cheud-726?

Example 2:

input = abcdefghijklmNOPQRSTUVWXYZ0123456789
rotationFactor = 39
output = nopqrstuvwxyzABCDEFGHIJKLM9012345678

Solution

class Solution {
    String rotationalCipher(String input, int rotationFactor) {
        StringBuilder sb = new StringBuilder();
        int n = input.length();
        for(int i=0; i<n; i++) {
            char c = input.charAt(i);
            if ('a' <= c && c <= 'z') {
                sb.append((char)('a' + (c - 'a' + rotationFactor)%26));
            }
            else if ('A' <= c && c <= 'Z') {
                sb.append((char)('A' + (c - 'A' + rotationFactor)%26));
            }
            else if ('0' <= c && c <= '9') {
                sb.append((char)('0' + (c - '0' + rotationFactor)%10));
            } else {
                sb.append(c);
            }

        }
        return sb.toString();
    }
}
Time Complexity: O(n)
Space Complexity: O(1)