用 C++ 将数字转换为负基表示形式
在本教程中,我们将讨论一个将数字转换为负基表示形式的程序。
为此,我们将提供一个数字和相应的负基。我们的任务是将给定的数字转换为其负基等价物。我们只允许负基值为 -2 到 -10 之间的数字。
示例
#include <bits/stdc++.h> using namespace std; //converting integer into string string convert_str(int n){ string str; stringstream ss; ss << n; ss >> str; return str; } //converting n to negative base string convert_nb(int n, int negBase){ //negative base equivalent for zero is zero if (n == 0) return "0"; string converted = ""; while (n != 0){ //getting remainder from negative base int remainder = n % negBase; n /= negBase; //changing remainder to its absolute value if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to string add into the result converted = convert_str(remainder) + converted; } return converted; } int main() { int n = 9; int negBase = -3; cout << convert_nb(n, negBase); return 0; }
输出
100
广告