Qt 将10进制数字与26进制(用A-Z来表示)之间相互转换
程序员文章站
2022-03-14 09:57:51
...
.h文件
#ifndef CONVERSIONOFNUMBERSYSTEM26_H
#define CONVERSIONOFNUMBERSYSTEM26_H
#include <QObject>
class conversionOfNumberSystem26 : public QObject
{
Q_OBJECT
public:
explicit conversionOfNumberSystem26(QObject *parent = nullptr);
static QString ToNumberSystem26(int n);
static int FromNumberSystem26(QString s);
signals:
};
#endif // CONVERSIONOFNUMBERSYSTEM26_H
.cpp文件
#include "conversionofnumbersystem26.h"
conversionOfNumberSystem26::conversionOfNumberSystem26(QObject *parent) : QObject(parent)
{
}
QString conversionOfNumberSystem26::ToNumberSystem26(int n)
{
QString s = "";
while (n > 0)
{
int m = n % 26;
if (m == 0)
{
m = 26;
}
s = (char)(m + 64) + s;
n = (n - m) / 26;
}
return s;
}
int conversionOfNumberSystem26::FromNumberSystem26(QString s)
{
if (s.isEmpty())
{
return 0;
}
int n = 0;
for (int i = s.length() - 1, j = 1; i >= 0; i--, j *= 26)
{
char c = s[i].toUpper().unicode(); //.unicode()是将QChar转为char
if (c < 'A' || c > 'Z')
{
return 0;
}
n += ((int)c - 64) * j;
}
return n;
}
上一篇: 先进先出队列,优先级队列以及后进先出队列
下一篇: 查找---二分查找