找出字母表中一个字母对应的数字

Figuring out the number corresponding to a letter of the alphabet?

本文关键字:数字 一个 字母表      更新时间:2023-10-16

我试图复制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)
相关文章: