Write an immutable Money class (amount in paise and a currency) whose operations return new objects, refuse to mix currencies, and allocate an amount into equal parts without losing paise.
Solution
main.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
class Money {
long long paise_;
std::string cur_;
public:
Money(long long paise, std::string cur) : paise_(paise), cur_(std::move(cur)) {}
Money operator+(const Money& o) const {
if (cur_ != o.cur_) throw std::invalid_argument("currency mismatch");
return {paise_ + o.paise_, cur_};
}
std::vector<Money> split(int parts) const {
std::vector<Money> out;
for (int i = 0; i < parts; ++i) // spread the remainder over the first parts
out.emplace_back(paise_ / parts + (i < paise_ % parts ? 1 : 0), cur_);
return out;
}
std::string str() const {
return cur_ + " " + std::to_string(paise_ / 100) + "." + (paise_ % 100 < 10 ? "0" : "") + std::to_string(paise_ % 100);
}
};
int main() {
const Money bill(100000, "INR"), tip(5000, "INR");
Money total = bill + tip;
for (const Money& share : total.split(3)) std::cout << share.str() << " | ";
std::cout << '\n' << bill.str() << '\n';
try { Money x = bill + Money(1000, "USD"); }
catch (const std::invalid_argument& e) { std::cout << e.what() << '\n'; }
return 0;
}
No member function changes an existing Money, so bill and tip can be shared safely. split hands the leftover paise to the first shares, so the parts always add up exactly to the total.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!