进制转换C++

进制转换部分可使用cstdlib库中的strtol():

#include 
#include
#include 

using namespace std;

int main()
{
	string s1 = "12a";
	//指向第一个未被识别出的字符。如16进制状态下,出现了字符f, 则指向该字符
	char * nptr;
	long a = strtol(s1.c_str(), &nptr, 16);

	cout << *nptr << endl;
	cout << a << endl;
	return 0;
}

 

进制转换C++_第1张图片

 进制转换C++_第2张图片

#include 
#include 
using namespace std;
/*
3
5 2 113221101000101
13 7 1016
4 12 2222248A
*/
int main()
{    
    int T;    //样例个数
    int X, Y; //进制
    string Z; //数据
    cin >> T;

    for (int i = 0; i < T; i++)
    {
        cin >> X >> Y;
        cin >> Z;
        size_t inLen = Z.length();
        size_t condit = X > Y ? inLen / 2 + 1 : inLen;
        for (size_t i = 1; i <= condit; i++)
        {
            string one = Z.substr(0, i);
            string two = Z.substr(i);
            
            int oneD = 0;
            for (size_t i = 0; i < one.size(); i++)
            {
                if (one[i] >= 'A')
                    oneD = oneD * X + (one[i] - 'A' + 10);
                else
                    oneD = oneD * X + (one[i] - '0');
            }
            
            int twoD = 0;
            for (size_t i = 0; i < two.size(); i++)
            {
                //类型转换成int类型
                if (two[i] >= 'A')
                    twoD = twoD * Y + (two[i] - 'A' +10);
                else
                    twoD = twoD * Y + (two[i] - '0');
                
            }
            if (oneD == twoD)
            {
                printf("%d\n", oneD);
                break;
            }
        }
    }
    return 0;
}

 

你可能感兴趣的:(C++)