Skip to content

Commit d1a9080

Browse files
authored
added methods charToPos and posToChar in MonoAlphabetic.java
1 parent e36f87c commit d1a9080

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

src/main/java/com/thealgorithms/ciphers/MonoAlphabetic.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,20 @@ public static String decrypt(String data, String key) {
3232

3333
for (char c : data.toCharArray()) {
3434
if (c >= 'A' && c <= 'Z') {
35-
int idx = key.indexOf(c); // Get the index in the key
36-
if (idx != -1) {
37-
char originalChar = (char) (idx + 'A'); // Convert index back to character
38-
sb.append(originalChar);
39-
}
40-
} else {
41-
sb.append(c); // Append non-alphabet characters directly
35+
int idx = charToPos(c); // Get the index in the key
36+
char encryptedChar = key.charAt(idx);
37+
sb.append(encryptedChar);
4238
}
43-
}
4439
return sb.toString();
4540
}
41+
42+
// Helper method: Convert a character to its position in the alphabet
43+
private static int charToPos(char c) {
44+
return c - 'A'; // Subtract 'A' to get position (0 for A, 1 for B, etc.)
45+
}
46+
47+
// Helper method: Convert a position in the alphabet to a character
48+
private static char posToChar(int pos) {
49+
return (char) (pos + 'A'); // Add 'A' to convert position back to character
50+
}
4651
}

0 commit comments

Comments
 (0)