From 0b5c3e48a6c420ab20b652df6159d74dd1135805 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Wed, 23 Mar 2022 22:11:27 +0800 Subject: [PATCH] add: 220323 [cpp] --- cpp/2203/220323.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 cpp/2203/220323.cpp diff --git a/cpp/2203/220323.cpp b/cpp/2203/220323.cpp new file mode 100644 index 0000000..fb03e71 --- /dev/null +++ b/cpp/2203/220323.cpp @@ -0,0 +1,22 @@ +#include + +/** + * 991. Broken Calculator + * There is a broken calculator that has the integer startValue on its display initially. In one operation, you can: + * - multiply the number on display by 2, or + * - subtract 1 from the number on display. + * Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator. + * + */ + +class Solution { +public: + static constexpr int brokenCalc(int startValue, int target) { + return (startValue >= target) ? startValue - target : 1 + ((target & 1) ? brokenCalc(startValue, target + 1) : brokenCalc(startValue, target / 2)); + } +}; + +int main() { + Solution s; + std::cout << s.brokenCalc(1, 1000000000) << "\n"; +}