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 | 321b890fa72435912af9456b072a90e1bff811fb (patch) | |
| tree | 0c963ef87e51f5f9e0230fbb281ccdf3f4b01a13 /works/solutions/cpp | |
| parent | 578f3da6699e07e2668ba74dc0caf0a16d293e37 (diff) | |
| download | crupest-321b890fa72435912af9456b072a90e1bff811fb.tar.gz crupest-321b890fa72435912af9456b072a90e1bff811fb.tar.bz2 crupest-321b890fa72435912af9456b072a90e1bff811fb.zip  | |
import(solutions): Add problem 397 .
Diffstat (limited to 'works/solutions/cpp')
| -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;
 +    }
 +};
  | 
