对两个N进制字符串求和

// nSystemStrSum.cpp : 定义控制台应用程序的入口点。
//
/*
N 进制的
两个字符串求和
字符串由0-9 a-z 组成
思路:
若输入不合法,输出提示退出,否则按如下步骤进行
1把两个字符串转成等成长,在短的那个串前加‘0’
2将串中的每一个字符转成数值
3从后到前 每一位临时变量= 串一的位+串二对应的位 +进位
此位上的数值 = 每一位临时变量%进制
        进位   = 每一位临时变量/进制
将数据转成字符  即systemValueStr[此位上的数值];
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
string systemValueStr = "0123456789abcdefghigklmnopkrstuvwxyz";
bool isLeal(string inputStr,int systemValue)//有效性     判断进制和输入的字符串是否在此进制范围内
{
    if (systemValue<2 || systemValue >35)
        return false;
    for (int i = 0; i < inputStr.length(); i++)
    {
        if (systemValue <= 10)
        {
            if (inputStr[i] - systemValueStr[0]<0 || (inputStr[i] - systemValueStr[systemValue]>0))
                return false;
            else if (!((inputStr[i] - '0' >= 0 && inputStr[i] - '0' <= 9) || ((inputStr[i] - 'a' >= 0 && inputStr[i] - 'a' + 10 <= systemValue-1))))
                return false;
        }
    }
}
int getIntFromString(char c,int systemValue){//将字符转成数值0~  进制-1
    if (c >= '0'&&c <= '9')
        return c - '0';
    else
        return c - 'a' + 10;
}
string addTwoStrOfNSystem(string inputStr1, string inputStr2, int systemValue){//求和
    string result = "";
    int len = max(inputStr1.length(), inputStr2.length());
    if (inputStr1.length() < inputStr2.length()){//补齐位数
        for (int i = inputStr1.length(); i < inputStr2.length(); i++)
        {
            inputStr1 = '0' + inputStr1;
        }
    }
    else if (inputStr1.length() >inputStr2.length())
    {
        for (int i = inputStr2.length(); i < inputStr1.length(); i++)
        {
            inputStr2 = '0' + inputStr2;
        }
    }
    int currentValue;
    int addNext = 0;
    for (int i = len - 1; i >= 0; i--)
    {
        int temp = getIntFromString(inputStr1[i], systemValue) + getIntFromString(inputStr2[i], systemValue) +addNext;
        currentValue = temp%systemValue;
        addNext = temp / systemValue;
        result = systemValueStr[currentValue] + result;

        
    }
    if (addNext > 0)
        result = systemValueStr[addNext] + result;
    return result;
}
void addTwoStr(){
    int system;//进制
    string inputStr1;
    string inputStr2;
    cout << "please into system" << endl;
    cin >> system;
    cout << "please input str1" << endl;
    cin>>inputStr1;
    cout << "please input str2" << endl;
    cin >> inputStr2;
    if (isLeal(inputStr1, system) && isLeal(inputStr2, system)){
        cout << addTwoStrOfNSystem(inputStr1, inputStr2, system) << endl;;
    }
    else
        cout << "please input right system and strs" << endl;


}

int _tmain(int argc, _TCHAR* argv[])
{
    addTwoStr();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/perfection2901/p/10562261.html
今日推荐