|
| 1 | +namespace BitManipulation |
| 2 | +{ |
| 3 | +// Given a positive integer n and you can do operations as follow: |
| 4 | + |
| 5 | +// If n is even, replace n with n/2. |
| 6 | +// If n is odd, you can replace n with either n + 1 or n - 1. |
| 7 | +// What is the minimum number of replacements needed for n to become 1? |
| 8 | + public class Solution |
| 9 | + { |
| 10 | + // Following coding refers to |
| 11 | + // A couple of Java solutions with explanations |
| 12 | + // But it has a bug of overflowing and I fix it. |
| 13 | + public int IntegerReplacement(int n) { |
| 14 | + int cnt = 0; |
| 15 | + long bign = (long)n; //n = Int32.MaxValue(2147483647),adds 1 and would overflow |
| 16 | + while (bign != 1) { |
| 17 | + if ((bign & 1) == 0) { //even number |
| 18 | + bign >>= 1; |
| 19 | + } |
| 20 | + //It is enough to examine the last two digits to figure out |
| 21 | + //whether incrementing or decrementing will give more 1's. Indeed, |
| 22 | + //if a number ends with 01, |
| 23 | + //then certainly decrementing is the way to go. Otherwise, if it ends with 11, |
| 24 | + //then certainly incrementing is at least as good as decrementing (*011 -> *010 / *100) or |
| 25 | + // even better (if there are three or more 1's). |
| 26 | + else if (bign == 3|| ((bign >> 1) & 1) == 0) { //*01 |
| 27 | + --bign; |
| 28 | + } |
| 29 | + else { //*11 |
| 30 | + ++bign; |
| 31 | + } |
| 32 | + ++cnt; |
| 33 | + } |
| 34 | + return cnt; |
| 35 | + } |
| 36 | + } |
| 37 | +} |
0 commit comments