Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลงตัวเลขเป็นการแสดงผลฐานลบ (Negative Base Representation) ใน C++

คำอธิบายปัญหา

ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมแปลงตัวเลขเป็นการแสดงผลฐานลบ (negative base representation)

สำหรับนี้ เราจะได้รับตัวเลขและฐานลบที่สอดคล้องกัน งานของเราคือแปลงตัวเลขที่กำหนดให้เป็นค่าเทียบเท่าในฐานลบ เราอนุญาตให้ค่าฐานลบอยู่ระหว่าง -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