안녕지구 #developer #bompapa

소소한팁 - 문자열을 숫자로 변환하기 2

|

글자를 숫자로 표현해야 하는 경우가 있습니다. 예를 들어서 aaa0으로 aab2로 표현할 수 있습니다. 다음은 소문자로 이뤄진 3자리 글자를 숫자로 표현하는 간단한 예입니다. 더 간단한 방법으로는 int hash[26][26][26] 의 배열로 표현할 수도 있습니다.

소문자는 a~z까지 총 26개이기 때문에 3글자면 총 17576(26*26*26)개로 0부터 17575까지 숫자로 표현할 수 있습니다.

구현

#include <iostream>
using namespace std;

int triple_to_int(const char* triple) {
	int ret = 0;
	ret += (triple[2] - 'a');
	ret += (triple[1] - 'a') * 26;
	ret += (triple[0] - 'a') * 26 * 26;
	return ret;
}

int main() {

	cout << triple_to_int("aaa") << endl;
	cout << triple_to_int("aab") << endl;
	cout << triple_to_int("zzy") << endl;
	cout << triple_to_int("zzz") << endl;

	return 0;
}

출력

0
1
17574
17575

Comments