2014-05-01 01:50
原题:
Microsoft Excel numbers cells as 1...26 and after that AA, AB.... AAA, AAB...ZZZ and so on. Given a number, convert it to that format and vice versa.
题目:微软的Office Excel对于每行每列的命名方式是1, 2, 3, ..., 26, AA, AB, ..., ZZ, AAA, ..., ZZZ。请写个函数完成这种“数字”和自然数的互相转换。
解法:数清楚每个长度“数字”的个数,然后分段转换即可。
代码:
1 // http://www.careercup.com/question?id=6139456847347712 2 #include <cstdio> 3 #include <iostream> 4 #include <string> 5 using namespace std; 6 7 string intToString(int n) 8 { 9 string s = ""; 10 11 if (n <= 26) { 12 while (n > 0) { 13 s.push_back(n % 10 + '0'); 14 n /= 10; 15 } 16 reverse(s.begin(), s.end()); 17 return s; 18 } 19 20 int exp; 21 int len; 22 23 exp = 26; 24 len = 1; 25 while (n > exp) { 26 n -= exp; 27 ++len; 28 exp *= 26; 29 } 30 31 --n; 32 for (int i = 0; i < len; ++i) { 33 s.push_back(n % 26 + 'A'); 34 n /= 26; 35 } 36 reverse(s.begin(), s.end()); 37 38 return s; 39 } 40 41 int stringToInt(const string &s) 42 { 43 int n = 0; 44 int len = (int)s.length(); 45 46 if (s[0] >= '0' && s[0] <= '9') { 47 sscanf(s.c_str(), "%d", &n); 48 return n; 49 } 50 51 int exp = 26; 52 53 for (int i = 1; i < len; ++i) { 54 n += exp; 55 exp *= 26; 56 } 57 exp = 0; 58 for (int i = 0; i < len; ++i) { 59 exp = exp * 26 + (s[i] - 'A'); 60 } 61 n += exp; 62 ++n; 63 64 return n; 65 } 66 67 int main() 68 { 69 int n; 70 string s; 71 72 while (scanf("%d", &n) == 1 && n > 0) { 73 s = intToString(n); 74 n = stringToInt(s); 75 cout << n << ' ' << s << endl; 76 } 77 78 return 0; 79 }