将数字转换为C ++中的负基表示
在本教程中,我们将讨论将数字转换为负数基数表示形式的程序。
为此,我们将提供一个数字和相应的负数基数。我们的任务是将给定的数字转换为其负的基数。对于负基本值,我们仅允许使用介于-2和-10之间的值。
示例
#include <bits/stdc++.h>
using namespace std;
//将整数转换为字符串
string convert_str(int n){
string str;
stringstream ss;
ss << n;
ss >> str;
return str;
}
//将n转换为负基
string convert_nb(int n, int negBase){
//零的负基当量为零
if (n == 0)
return "0";
string converted = "";
while (n != 0){
//从负数中减去余数
int remainder = n % negBase;
n /= negBase;
//将余数更改为其绝对值
if (remainder < 0) {
remainder += (-negBase);
n += 1;
}
//将余数转换为字符串,将其添加到结果中
converted = convert_str(remainder) + converted;
}
return converted;
}
int main() {
int n = 9;
int negBase = -3;
cout << convert_nb(n, negBase);
return 0;
}输出结果
100