diff options
author | crupest <crupest@outlook.com> | 2020-07-24 16:28:02 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-07-24 16:28:02 +0800 |
commit | 9b8c27b2ce259dfbd041a000d9b31d168cac18bd (patch) | |
tree | 48132b0b52f03a7c904ee3a197174ee2baaeabc6 /cpp/397.cpp | |
parent | 9a2973f54307548c78385e674fa1d002ed6e2689 (diff) | |
download | solutions-9b8c27b2ce259dfbd041a000d9b31d168cac18bd.tar.gz solutions-9b8c27b2ce259dfbd041a000d9b31d168cac18bd.tar.bz2 solutions-9b8c27b2ce259dfbd041a000d9b31d168cac18bd.zip |
Add problem 397 .
Diffstat (limited to 'cpp/397.cpp')
-rw-r--r-- | cpp/397.cpp | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/cpp/397.cpp b/cpp/397.cpp new file mode 100644 index 0000000..bbb61ff --- /dev/null +++ b/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;
+ }
+};
|