From 321b890fa72435912af9456b072a90e1bff811fb Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 24 Jul 2020 16:28:02 +0800 Subject: import(solutions): Add problem 397 . --- works/solutions/cpp/397.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 works/solutions/cpp/397.cpp (limited to 'works/solutions/cpp/397.cpp') diff --git a/works/solutions/cpp/397.cpp b/works/solutions/cpp/397.cpp new file mode 100644 index 0000000..bbb61ff --- /dev/null +++ b/works/solutions/cpp/397.cpp @@ -0,0 +1,47 @@ +class Solution +{ +public: + int integerReplacement(int n) + { + if (n == 2147483647) + return 32; + + int count = 0; + + while (n != 1) + { + if (n == 2) + { + count += 1; + break; + } + if (n == 3) + { + count += 2; + break; + } + if (n % 2 == 0) + { + count += 1; + n /= 2; + continue; + } + if ((n - 1) % 4 == 0) + { + count += 3; + n = (n - 1) / 4; + continue; + } + if ((n + 1) % 4 == 0) + { + count += 3; + n = (n + 1) / 4; + continue; + } + count += 2; + n = (n - 1) / 2; + } + + return count; + } +}; -- cgit v1.2.3