Implement and test the class named Ternary according to the following class defi
ID: 3587716 • Letter: I
Question
Implement and test the class named Ternary according to the following class definition:
class Ternary {
public:
Ternary();
Ternary(int);
Ternary& operator+=( const Ternary&);
Ternary& operator-=( const Ternary&);
Ternary& operator*=(const Ternary&);
Ternary& operator-();
bool operator==(const Ternary&) const;
bool operator!=(const Ternary&) const;
bool operator<(const Ternary&) const;
bool operator>(const Ternary&) const;
bool operator<=(const Ternary&) const;
bool operator>=(const Ternary&) const;
istream& extract(istream&);
ostream& insert(ostream&) const;
private:
bool isTernary(int) const;
int toDecimal(int) const;
int toTernary(int) const;
int decimal_equivalent;
};
ostream& operator<<(ostream&, const Ternary&);
istream& operator>>(istream&, Ternary&);
const Ternary& operator+(const Ternary&, const Ternary&);
const Ternary& operator-(const Ternary&, const Ternary&);
const Ternary& operator*(const Ternary&, const Ternary&);
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
class Ternary{
int num; // Num is your only private data member
public:
Ternary(){
num = 0;
}
Ternary(int n){ // Convert Base 3 number to Decimal number
int temp = 0, base = 1;
while(n){
int rem = n % 10;
if(rem > 2){ // If anytime rem > 2 number is Invalid
cout << "Invalid Ternary Number : " << rem <<endl;
return;
}
temp += (rem * base);
base *= 3;
n /= 10;
}
num = temp;
}
Ternary plus(const Ternary& r) const;
Ternary minus(const Ternary& r) const;
Ternary times(const Ternary& r) const;
void insert(ostream&);
void extract(istream&);
};
Ternary Ternary::plus(const Ternary& r) const{ // Add number and store it to another number
int a = r.num;
int b = num;
int res = 0 , sum = a+b;
while(sum){ // First convert sum to base 3
res = (res * 10) + sum%3;
sum /= 3;
}
return Ternary(res);
}
Ternary Ternary::minus(const Ternary& r) const{
int a = r.num;
int b = num;
int res = 0 , sub = b - a;
while(sub){ // Convert Subtraction to Base 3
res = (res * 10) + sub%3;
sub /= 3;
}
return Ternary(res);
}
Ternary Ternary::times(const Ternary& r) const{
int a = r.num;
int b = num;
int res = 0 , sub = b * a;
while(sub){ // Convert Times result to Base 3
res = (res * 10) + sub%3;
sub /= 3;
}
return Ternary(res);
}
void Ternary::insert(ostream& out){
out << num << endl;
return;
}
void Ternary::extract(istream& in){
in >> num;
return;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.