fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. private static final class CypherText {
  12. private final int key;
  13. private final String text;
  14.  
  15. public CypherText(int key, String text) {
  16. super();
  17. this.key = key;
  18. this.text = text;
  19. }
  20.  
  21. public int getKey() {
  22. return key;
  23. }
  24.  
  25. public String getText() {
  26. return text;
  27. }
  28.  
  29. }
  30.  
  31. public static CypherText getEncoded() {
  32. int k = Integer.parseInt(reader.readLine());
  33. String word = reader.readLine();
  34. return new CypherText(k, word);
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. return new CypherText(0, "");
  38. }
  39. }
  40.  
  41. public static final String decode(final int key, final String encoded) {
  42. final int len = encoded.length();
  43. char[] decoded = new char[len];
  44. for (int i = 0; i < len; i++) {
  45. decoded[i] = decodeChar(encoded.charAt(i), i + 1, key);
  46. }
  47. return new String(decoded);
  48. }
  49.  
  50. private static char decodeChar(final char encoded, final int position, final int key) {
  51. // modulo 26 eliminates multiple wrap-arounds.
  52. int rotate = (3 * position + key) % 26;
  53. // apply the rotation shift to the input
  54. int decval = (encoded - 'A') + 26 - rotate;
  55. // use another % 26 to keep the letters in range.
  56. return (char)('A' + (decval % 26));
  57. }
  58.  
  59. public static void main(String[] args) {
  60. CypherText input = getEncoded();
  61. String decoded = decode(input.getKey(), input.getText());
  62. System.out.println("Decoded: " + decoded);
  63. }
  64.  
  65.  
  66. }
Success #stdin #stdout 0.06s 380160KB
stdin
5
JTUSUKG
stdout
Decoded: BIGBANG