Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1b06b5f

Browse files
Today update
1 parent c9b1540 commit 1b06b5f

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

‎TodayUpdate.md

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,31 @@
33
https://github.com/jackzhenguo/LeetCodeManager
44

55
## Bit Mainpulation
6-
* [CSDN:#476 Number Complement](http://blog.csdn.net/daigualu/article/details/72843822)
7-
> get bits for a number</br>
6+
* [CSDN:#397 Integer Replacement](http://blog.csdn.net/daigualu/article/details/72861851)
7+
> Following coding refers to A couple of Java solutions with explanations
8+
> But it has a bug of overflowing and I fix it.</br>
89
```C#
9-
public int FindComplement(int num)
10-
{
11-
int bits = 1; //num including bits
12-
while (Math.Pow(2, bits) <= num)
13-
bits++;
14-
int sum = (int) Math.Pow(2, bits) - 1;//sum =Pow(2,n)-1: sum of n bits 1
15-
return sum - num; //sum - num is the complement
16-
10+
public int IntegerReplacement(int n) {
11+
int cnt = 0;
12+
long bign = (long)n; //n = Int32.MaxValue(2147483647),adds 1 and would overflow
13+
while (bign != 1) {
14+
if ((bign & 1) == 0) { //even number
15+
bign >>= 1;
16+
}
17+
//It is enough to examine the last two digits to figure out
18+
//whether incrementing or decrementing will give more 1's. Indeed,
19+
//if a number ends with 01,
20+
//then certainly decrementing is the way to go. Otherwise, if it ends with 11,
21+
//then certainly incrementing is at least as good as decrementing (*011 -> *010 / *100) or
22+
// even better (if there are three or more 1's).
23+
else if (bign == 3|| ((bign >> 1) & 1) == 0) { //*01
24+
--bign;
25+
}
26+
else { //*11
27+
++bign;
1728
}
29+
++cnt;
30+
}
31+
return cnt;
32+
}
1833
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /