在这个问题上,给出了两个数字。这些数字的底数为n。我们还必须在以n为底的加法中找到这些数字的结果。
首先,将数字转换为十进制数字。从十进制值中,我们可以简单地将它们相加。最后,数字再次转换为以n为底的数字。
n个基数以字符串形式给出,因为对于那些基数大于9的数字,它可能包含一些字母来表示数字,例如十六进制数字,则有6个字母(AF)。
Input: The base of a number system: 16 First number 2C Second number 5F Output: The result of addition is: 8B
baseNtoDec(number,base)
输入-以N为底的数字字符串,以N为底的值。
输出-以N为底的数字的十进制等效项。
Begin len := length of number power := 1 num := 0 for i := len -1 down to 0, do if number[i] >= base, then return invalid number num := num + number[i] * power power := power * base done return num End
decToBaseN(dec,base)
输入:十进制数,以N为基数的十进制数。
输出:以N为底的数字字符串。
Begin while dec > 0, do res := concatenate (dec mod base) with res dec := dec / base done reverse the result return res End
addBaseN(num1,num2,base)
输入: 以N为底的两个数字,即N的值。
输出: 加N后的数字。
Begin dec1 := baseNtoDec(num1, base) dec2 := baseNtoDec(num2, base) sum := decToBaseN(dec1 + dec2, base) return sum End
#include<iostream> #include<algorithm> using namespace std; int getVal(char c) { if(c >= '0' && c<='9') return int(c-'0'); //decimal value of given number else return int(c-'A'+10); //for Alphanumeric numbers } char revVal(int n) { if(n >= 0 && n <=9) return char(n+'0'); //character value of given number else return char(n+'A'-10); //for Alphanumeric numbers, get alphabet from decimal } int baseNtoDec(string number, int base) { int len = number.size(); int power = 1; int num = 0; for(int i = len-1; i>= 0; i--) { //from last digit to first digit if(getVal(number[i]) >= base) return INT_MIN; //when a digit is >= base, return -ve infinity as error num += getVal(number[i])*power; power = power*base; } return num; } string decToBaseN(int dec, int base) { string res = ""; //empty string while(dec > 0) { res += revVal(dec%base); dec /= base; } reverse(res.begin(), res.end()); //reverse the string to get final answer return res; } int main() { int base; string num1, num2, sum; cout << "Enter Base: "; cin >> base; cout << "Enter first number in base "<<base<<": ";cin >> num1; cout << "Enter second number in base "<<base<<": ";cin >> num2; sum = decToBaseN((baseNtoDec(num1, base) + baseNtoDec(num2, base)), base); cout << "The result of addition is: " << sum; }
输出结果
Enter Base: 16 Enter first number in base 16: 2C Enter second number in base 16: 5F The result of addition is: 8B