Skip to content

Commit a300d2f

Browse files
committed
add leetcode: offer-15-33-65
1 parent a8beb2f commit a300d2f

3 files changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-13-15:34
6+
* @Function Description :15.二进制中1的个数
7+
*/
8+
public class _15TheNumberOf1InBinary {
9+
public class Solution {
10+
// you need to treat n as an unsigned value
11+
public int hammingWeight(int n) {
12+
int res = 0;
13+
// 注意!!!!n有可能是负数!!!!所以用不等于0判断,不能写n>0
14+
while( n != 0 ){
15+
if( (n & 1) == 1 ) res++;
16+
// res += n & 1;//另外一种写法
17+
n >>>= 1;
18+
}
19+
return res;
20+
}
21+
}
22+
23+
//==========================n &= n - 1============================
24+
public class Solution2 {
25+
// you need to treat n as an unsigned value
26+
public int hammingWeight(int n) {
27+
int res = 0;
28+
while( n != 0 ){
29+
res++;
30+
// n & (n - 1) 每次消去最右边的1
31+
n = n & (n - 1 );
32+
}
33+
return res;
34+
}
35+
}
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-13-15:24
6+
* @Function Description :33. 二叉搜索树的后序遍历序列
7+
*/
8+
public class _33ThePostOrderSequenceOfTheBinarySearchTree {
9+
class Solution {
10+
public boolean verifyPostorder(int[] postorder) {
11+
return recur(postorder , 0 , postorder.length - 1 );
12+
}
13+
14+
// 递归后序序列是否满足二叉搜索树的性质,(i,j)是从i到j一个左右根的范围
15+
public boolean recur( int[] postorder , int i , int j ){
16+
if( i >= j ) return true;
17+
//
18+
int p = i ;
19+
// 找到左子树的左边界,也就是拿左右根的初始范围起点跟根结点比较,小于的都在左子树,直到大于等于
20+
while( postorder[p] < postorder[j] ) p++;
21+
// m记录下左子树的边界终点
22+
int m = p;
23+
// p继续遍历,找右子树的边界终点,起点就是上面遍历完左子树的终点
24+
while( postorder[p] > postorder[j] ) p++;
25+
// p最后走到j根处,并且以m划分的左右子树都符合判断的情况
26+
return p == j && recur( postorder , i , m - 1 ) && recur( postorder , m , j - 1 );
27+
}
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-13-15:53
6+
* @Function Description :65.不用加减乘除做加法
7+
*/
8+
public class _65NoAddSubtractMultiplyAndDoAddition {
9+
class Solution {
10+
public int add(int a, int b) {
11+
/*
12+
没有进位的加法相当于异或运算,有进位的相当于与运算然后左移1位。
13+
最后的和就是两者相加,直到进位为0
14+
*/
15+
while( b != 0 ){
16+
// c记录进位情况
17+
int c = ( a & b ) << 1;
18+
// 进行一轮加法运算
19+
a ^= b;
20+
// b更新剩余进位
21+
b = c;
22+
}
23+
return a;
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)