用 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

更新於:06-01-2020

201 次瀏覽

開啟 事業旅程

完成課程獲取認證

開始吧
廣告
© . All rights reserved.