Related questions
#include <iostream>
#include <string>
#include <climits>
using namespace std;
class BalancedTernary {
protected:
// Store the value as a reversed string of +, 0 and - characters
string value;
// Helper function to change a balanced ternary character to an integer
int charToInt(char c) const {
if (c == '0')
return 0;
return 44 - c;
}
// Helper function to negate a string of ternary characters
string negate(string s) const {
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '+')
s[i] = '-';
else if (s[i] == '-')
s[i] = '+';
}
return s;
}
public:
// Default constructor
BalancedTernary() {
value = "0";
}
// Construct from a string
BalancedTernary(string s) {
value = string(s.rbegin(), s.rend());
}
// Construct from an integer
BalancedTernary(long long n) {
if (n == 0) {
value = "0";
return;
}
bool neg = n < 0;
if (neg)
n = -n;
value = "";
while (n != 0) {
int r = n % 3;
if (r == 0)
value += "0";
else if (r == 1)
value += "+";
else {
value += "-";
++n;
}
n /= 3;
}
if (neg)
value = negate(value);
}
// Copy constructor
BalancedTernary(const BalancedTernary & n) {
value = n.value;
}
// Addition operators
BalancedTernary operator + (BalancedTernary n) const {
n += * this;
return n;
}
BalancedTernary & operator += (const BalancedTernary & n) {
static char * add = "0+-0+-0";
static char * carry = "--000++";
int lastNonZero = 0;
char c = '0';
for (int i = 0; i < value.length() || i < n.value.length(); ++i) {
char a = i < value.length() ? value[i] : '0';
char b = i < n.value.length() ? n.value[i] : '0';
int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3;
c = carry[sum];
if (i < value.length())
value[i] = add[sum];
else
value += add[sum];
if (add[sum] != '0')
lastNonZero = i;
}
if (c != '0')
value += c;
else
value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes
return *this;
}
// Negation operator
BalancedTernary operator - () const {
BalancedTernary result;
result.value = negate(value);
return result;
}
// Subtraction operators
BalancedTernary operator - (const BalancedTernary & n) const {
return operator + (-n);
}
BalancedTernary & operator -= (const BalancedTernary & n) {
return operator += (-n);
}
// Multiplication operators
BalancedTernary operator * (BalancedTernary n) const {
n *= * this;
return n;
}
BalancedTernary & operator *= (const BalancedTernary & n) {
BalancedTernary pos = * this;
BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly
value = "0";
for (int i = 0; i < n.value.length(); ++i) {
if (n.value[i] == '+')
operator += (pos);
else if (n.value[i] == '-')
operator += (neg);
pos.value = '0' + pos.value;
neg.value = '0' + neg.value;
}
return *this;
}
// Stream output operator
friend ostream & operator << (ostream & out,
const BalancedTernary & n) {
out << n.toString();
return out;
}
// Convert to string
string toString() const {
return string(value.rbegin(), value.rend());
}
// Convert to integer
long long toInt() const {
long long result = 0;
for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3)
result += pow * charToInt(value[i]);
return result;
}
// Convert to integer if possible
bool tryInt(long long & out) const {
long long result = 0;
bool ok = true;
for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) {
if (value[i] == '+') {
ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows
result += pow;
} else if (value[i] == '-') {
ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows
result -= pow;
}
}
if (ok)
out = result;
return ok;
}
};
int main() {
int num, num1, num2, num3;
cout << "enter a: ";
cin >> num;
cout << "enter b: ";
cin >> num1;
cout << "enter c: ";
cin >> num2;
BalancedTernary a(num);
BalancedTernary b(num1);
BalancedTernary c(num2);
cout << "a = " << a.toInt() << " = " << a.toInt() << endl;
cout << "b = " << b.toInt() << " = " << b.toInt() << endl;
cout << "c = " << c.toInt() << " = " << c.toInt() << endl;
cout << "\n";
cout << a.toInt() << " = " << a.toInt() << endl;
BalancedTernary z = c - a;
cout << z.toInt() << " = " << c.toInt() << " - " << a.toInt() << endl;
cout << c.toInt() << " = " << c.toInt() << endl;
BalancedTernary y = c + a;
cout << y.toInt() << " = " << c.toInt() << " + " << a.toInt() << endl;
cout << "\n";
BalancedTernary d = a + b * c;
cout << "a + b * c = " << d.toInt() << "=" << d.toInt() << endl;
return 0;
}
Can I get an clear explaination of this program with and
Trending nowThis is a popular solution!
Step by stepSolved in 4 steps with 2 images
- // MichiganCities.cpp - This program prints a message for invalid cities in Michigan. // Input: Interactive // Output: Error message or nothing #include <iostream> #include <string> using namespace std; int main() { // Declare variables string inCity; // name of city to look up in array const int NUM_CITIES = 10; // Initialized array of cities string citiesInMichigan[] = {"Acme", "Albion", "Detroit", "Watervliet", "Coloma", "Saginaw", "Richland", "Glenn", "Midland", "Brooklyn"}; bool foundIt = false; // Flag variable int x; // Loop control variable // Get user input cout << "Enter name of city: "; cin >> inCity; // Write your loop here // Write your test statement here to see if there is // a match. Set the flag to true if city is found. // Test to see if city was not found to determine if // "Not a city in Michigan" message should be printed....arrow_forward#include #include #include "Product.h" using namespace std; int main() { vector productList; Product currProduct; int currPrice; string currName; unsigned int i; Product resultProduct; cin>> currPrice; while (currPrice> 0) { } cin>> currPrice; main.cpp cin>> currName; currProduct.SetPriceAndName (currPrice, currName); productList.push_back(currProduct); resultProduct = productList.at (0); for (i = 0; i < productList.size(); ++i) { Type the program's output Product.h 1 CSE Scanned Product.cpp if (productList.at (i).GetPrice () < resultProduct.GetPrice ()) { resultProduct = productList.at(i); } AM cout << "$" << resultProduct.GetPrice() << " " << resultProduct. GetName() << endl; return 0; Input 10 Cheese 6 Foil 7 Socks -1 Outputarrow_forwardProgramming Problems doubleVowel Write a function doublevowel that accepts a word as an argument and returns True if the word contains two adjacent vowels and False otherwise. Sample usage:>>> doublevowel ('apple') False>>> doubleVowel ('pear') True>>> doubleVowel ('pear') True>>> doublevowe]('DURIAN') True>>> doublevowel ('baNaNa') False>>> doubleVowel ('baNaNa')== False Truearrow_forward
- Write a function getNeighbors which will accept an integer array, size of the array and an index as parameters. This function will return a new array of size 2 which stores the neighbors of the value at index in the original array. If this function would result in returning garbage values the new array should be set to values {0,0} instead of values from the array.arrow_forward3. int count(10); while(count>= 0) { count -= 2; std::cout << count << endl;arrow_forwardC++ complete magic Square #include <iostream> using namespace std; /*int f( int x, int y, int* p, int* q ){if ( y == 0 ){p = 0, q = 0;return 404; // status: Error 404}*p = x * y; // product*q = x / y; // quotient return 200; // status: OK 200} int main(){int p, q;int status = f(10, 2, &p, &q);if ( status == 404 ){cout << "[ERR] / by zero!" << endl;return 0;}cout << p << endl;cout << q << endl; return 0;}*/ /*struct F_Return{int p;int q;int status;}; F_Return f( int x, int y ){F_Return r;if ( y == 0 ){r.p = 0, r.q = 0;r.status = 404;return r;}r.p = x * y;r.q = x / y;r.status = 200;return r;} int main(){F_Return r = f(10, 0);if ( r.status == 404 ){cout << "[ERR] / by zero" << endl;return 0;}cout << r.p << endl;cout << r.q << endl;return 0;}*/ int sumByRow(int *m, int nrow, int ncol, int row){ int total = 0;for ( int j = 0; j < ncol; j++ ){total += m[row * ncol + j]; //m[row][j];}return total; } /*...arrow_forward
- In C++ struct myGrades { string class; char grade; }; Declare myGrades as an array that can hold 5 sets of data and then set a class string in each position as follows: "Math" "Computers" "Science" "English" "History" and give each class a letter gradearrow_forward#include using namespace std; void scanPrice (string [], double []); // Do not modify the code double printReceipt(string [], double[]); // Do not modify the code int main () { double sum; string item [3] = {"Vegetable","Egg", "Meat"}; double price [3];| %3D scanPrice (item,price); sum = RrintReceipt (item,price); cout Price: 10 The price of Vegetable is RM 2 The price of Egg is RM 3 The price of Meat is RM 10 Your total expenses is RM 15arrow_forward#include <bits/stdc++.h> using namespace std; struct Employee { string firstName; string lastName; int numOfHours; float hourlyRate; char major[2]; float amount; Employee* next; }; void printRecord(Employee* e) { cout << left << setw(10) << e->lastName << setw(10) << e->firstName << setw(12) << e->numOfHours << setw(12) << e->hourlyRate << setw(10) << e->amount << setw(9) << e->major[0]<< setw(7) << e->major[1]<<endl; } void appendNode(Employee*& head, Employee* newNode) { if (head == nullptr) { head = newNode; } else { Employee* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode; } } void displayLinkedList(Employee* head) { Employee* current = head; if(current!=nullptr){ cout...arrow_forward
- C++ Coding: ArraysTrue and False Code function definitions for eoNum() and output(): Both eoNum() and output() are recursive functions. output() stores the even/odd value in an array. Store 0 if the element in the data array is even and store 1 if the element in the data array is odd. eoNum() displays all the values in an array to the console.arrow_forward#ifndef INT_SET_H#define INT_SET_H #include <iostream> class IntSet{public: static const int DEFAULT_CAPACITY = 1; IntSet(int initial_capacity = DEFAULT_CAPACITY); IntSet(const IntSet& src); ~IntSet(); IntSet& operator=(const IntSet& rhs); int size() const; bool isEmpty() const; bool contains(int anInt) const; bool isSubsetOf(const IntSet& otherIntSet) const; void DumpData(std::ostream& out) const; IntSet unionWith(const IntSet& otherIntSet) const; IntSet intersect(const IntSet& otherIntSet) const; IntSet subtract(const IntSet& otherIntSet) const; void reset(); bool add(int anInt); bool remove(int anInt); private: int* data; int capacity; int used; void resize(int new_capacity);}; bool operator==(const IntSet& is1, const IntSet& is2); #endifarrow_forward#include <iostream> #include <string> #include <cstdlib> using namespace std; template<class T> class A { public: T func(T a, T b){ return a/b; } }; int main(int argc, char const *argv[]) { A <float>a1; cout<<a1.func(3,2)<<endl; cout<<a1.func(3.0,2.0)<<endl; return 0; } Give output for this code.arrow_forward
- Text book imageDatabase System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationText book imageStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONText book imageDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- Text book imageC How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONText book imageDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningText book imageProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education