From 185ef9fcb0e59f13e9ee0ccb261693cdaddebab0 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 23 Feb 2021 21:07:19 +0800 Subject: import(solutions): Move leetcode solutions to subdir. --- works/solutions/leetcode/cpp/397.cpp | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 works/solutions/leetcode/cpp/397.cpp (limited to 'works/solutions/leetcode/cpp/397.cpp') diff --git a/works/solutions/leetcode/cpp/397.cpp b/works/solutions/leetcode/cpp/397.cpp new file mode 100644 index 0000000..bbb61ff --- /dev/null +++ b/works/solutions/leetcode/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