[JAVA] Handle letters ⇔ numbers

Introduction

In this article, I found a good problem in CodeWars to get used to the technique of treating char type characters as numbers, so I would like to introduce it.

Problem URL

Reversing a Process

Summary: The problem of coding the reverse operation of the process of converting a string according to rules. (I'm wondering if it can be summarized ...)

AC cord

Decode.java


class Decode { 
    public static String decode(String r) {
       int numkey = 0;
       String subs = "";
       for(int i = 0;i < r.length();i++) {
         if(r.charAt(i)-'a'>=0) {
           numkey = Integer.parseInt(r.substring(0,i));
           subs = r.substring(i);
           break;
         }
       }
       char[] ch = subs.toCharArray();
       StringBuilder sb = new StringBuilder();
       for(int i = 0;i < ch.length;i++) {
         for(int j = 0;j < 26;j++) {
           if(j*numkey%26==ch[i]-'a') {
             sb.append((char)(j+'a'));
           }
         }
       }
       if(sb.length() != ch.length) {
         sb.delete(0, sb.length());
         sb.append("Impossible to decode");
       }
       return sb.toString();
    }
}

Commentary

--First, divide the number part (numkey) that becomes the conversion key and the character string (subs) after conversion. At this time, it is used that (character code number of Arabic numeral) <(character code number of alphabet).

--Search for each character in the range of 0 to 25 (number of alphabets), add the character code of a to the number that meets the conditions, and charcast to make it a character. (Since the character code increases by 1 in order from a, the character corresponding to j can be restored by adding the number of character codes of a to the hit j. character code of ex. a: 0097 If j = 2, j +'a'= 0099 →'c')

--Sequentially combine characters, and if the decoded character string length does not match the original character string length, substitute "Impossible to decode". (* When the number keys are multiples of 2 or 13, they will not match.)

The above operation worked correctly and I was able to take AC.

Afterword

Since I learned multiple techniques for handling letters, I thought this problem was a good teaching material to get used to handling char. If you have something like "You can make it smarter!" Or "There is such a way!", Please comment.

Recommended Posts

Handle letters ⇔ numbers
Count letters