找出对应于字母表的字母的数字?
我试图重复Excel的方式提供标签的列在哪里
A = 1
B = 2
如此等等,以至于它最终到达
AB
AC
广告
等等
我如何algorithm地采取一个数字(如52),并将其转换为其等效的字母表示?
string get(int a) { a--; // Reduce by one to make the values with 1 letter 0..25, // with two - 26.. 26^2-1 and so on int val = 0; // number of columns with no more then given number of letters int number = 0; while (val < a) { val = val*26 + 26; number++; } val = (val - 26)/26; a -= val; // subtract the number of columns with less letters string res; for (int i = 0; i < number; ++i) { res.push_back(a%26 + 'A'); a /= 26; } reverse(res.begin(), res.end()); return res; }
希望有所帮助。
两个字母
#include <iostream> #include <string> using namespace std; string int2alphas(int i) { string res; if (i > 26 - 1) res.push_back(i / 26 + 'A' - 1); else res.push_back(' '); res.push_back(i % 26 + 'A'); return res; } void test(int t) { cout << t << "-" << int2alphas(t) << endl;; } int main() { for (int i = 0; i < 55; i++) test(i); }
Convert.ToInt32(“52”,26)….现在只需创build正确的基本实现。 ? 家庭作业 ?
你可能会想到写一些algorithm,如:
ConvertToAlphaCode(number input) { Array Chars=[AZ] if (number<= 26) return Chars[number-1] else ... }
看一看:
A, B, C, D, ..., Y, Z, AA, AB, AC, AD, ..., AY, AZ, BA, BB, ...
完全一样:
0, 1, 2, 3, 4, ..., 9, 10, 11, 12, 13, ..., 19, 20, 21, ...
但数字A..Z
而不是0..9
。 所以:
algorithm,我不知道我怎么能得到一个数字,如说52,并将其转换为等效的字母表示。
您需要使用通用algorithm将base-N中的数字转换为base -M(如十进制到hex),但N等于10,M等于26(字母),并确保使用正确的字符代表最后的“数字”。 就如此容易!
这将做得很好:
string calcString(int number) { string returnValue = ""; do { int rm = number % 26; returnValue += (char)(rm+ 'A'); number = (number - rm) / 26; } while (number > 0); return returnValue; }
例如, calcString(11);
结果在L
如果这不是你正在寻找的计算,留下评论来澄清你想要什么,我会回来改变它。
从数字到字母:
static std::string const letters( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); assert( n >= 0 && n < letters.size() ); return letters[n];
从字母到数字:
static std::string const letters( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); char const* result = std::find( letters.begin(), letters.end(), isupper( static_cast< unsigned char >( l ) ); assert( result != letters.end() ); return result - letters.begin();
编辑:
这只是处理每个方向的单个字符。 更多的,这只是一个基本的26转换,使用通常的转换例程。
这将适用于所有types的字母(小,大)。
using namespace std; int lettervalue (string l) { l=l[0]; string alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int idx = alpha.find(l)+1; if(idx>26){ idx=idx-26; } return idx; }
要使用它:
cout << lattervalue("e"); //will return 5(int)