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 | 23c405d2a51119263f0c33780f739234e4e54889 (patch) | |
tree | d587a0cf59e19ee99b2b6af543c6f3f49c623b72 | |
parent | 25625c4f2e6af2836af27d8c2678f516b768fb5b (diff) | |
download | crupest-23c405d2a51119263f0c33780f739234e4e54889.tar.gz crupest-23c405d2a51119263f0c33780f739234e4e54889.tar.bz2 crupest-23c405d2a51119263f0c33780f739234e4e54889.zip |
import(solutions): Add problem 397 .
-rw-r--r-- | works/solutions/cpp/397.cpp | 47 |
1 files changed, 47 insertions, 0 deletions
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;
+ }
+};
|