找出字母表中一个字母对应的数字
Figuring out the number corresponding to a letter of the alphabet?
我试图复制excel提供标签的方式
A = 1
B = 2
等等,最终到达
AB
交流
广告
等等。
我如何在算法上取一个数字(如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);
}
转换。ToInt32("52",26)……现在创建正确的基本实现。? 作业吗?
你可以考虑写一些算法:
ConvertToAlphaCode(number input)
{
Array Chars=[A-Z]
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
。所以:
从算法上讲,我不确定如何获得一个数字,比如52,并将其转换为等效的字母表表示。
您需要使用通用算法将以N为基数的数字转换为以M为基数的数字(如十进制转换为十六进制),但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进制的转换,使用通常的转换例程。
这适用于所有类型的字母(小,大)
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)
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 我想做一个彼此不同但重复出现的数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- CIN 仅在输入非数字值时跳过下一个 CIN
- 以C++输出一个数字三角形
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 将数字提高到一个巨大的指数
- 反转一个数字程序不起作用,为什么?
- 使用带有一个参数函数的递归找到数字的平方
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作