소소한팁 - 문자열을 숫자로 변환하기 2
28 Aug 2020 | 알고리즘 소소한팁글자를 숫자로 표현해야 하는 경우가 있습니다. 예를 들어서 aaa 는 0으로 aab는 2로 표현할 수 있습니다. 다음은 소문자로 이뤄진 3자리 글자를 숫자로 표현하는 간단한 예입니다. 더 간단한 방법으로는 int hash[26][26][26] 의 배열로 표현할 수도 있습니다.
구현
#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