엑셀 암호

Ajisai·2023년 8월 2일
0

etc

목록 보기
4/8
import java.io.*;
import java.util.*;

import java.math.BigInteger;

public class Main {
	public static void main(String[] args) {
		String encoded = encode("ABCD");
		System.out.println(encoded);
		System.out.println(decode(encoded));
	}

	public static String decode(String n) {
		if(!n.matches("[0-9]+")) return null;

		StringBuilder sb = new StringBuilder();
		BigInteger temp = new BigInteger(n);
		BigInteger diff = BigInteger.valueOf(26L);
		do {
			int val = BigInteger.valueOf((long)'A')
					.add(
						diff.add(temp.mod(diff))
						.subtract(BigInteger.ONE)
						.mod(diff)
					)
					.intValue();
			
			char c = (char) val;

			sb.append(c);
			if(c == 'Z') temp = temp.subtract(BigInteger.ONE);
		} while(!(temp = temp.divide(diff)).equals(BigInteger.ZERO));

		return sb.reverse().toString();
	}

	public static String encode(String str) {
		if(!str.matches("[A-Z]+")) return "-1";

		BigInteger res = BigInteger.ZERO;
		BigInteger j = BigInteger.ONE;
		for(int i = str.length() - 1; i >= 0; j = j.multiply(BigInteger.valueOf(26L)), i--) {
			res = res.add(BigInteger.valueOf(str.charAt(i) - 'A' + 1).multiply(j));
		}

		return res.toString();
	}
}

자세한 내용은 여기 참고.

profile
Java를 하고 싶었지만 JavaScript를 하게 된 사람

0개의 댓글

관련 채용 정보