最近被问到的算法整理

题目:

1、取一个整数a从右端开始的4~7位

解题思路:

比如一个数 00000000 00000000 00000000 00000100 要取出4-7位,
我们可以先用&来把其他的位数化成0,然后只保留4-7位为1,
也就是我们可以&的数为00000000 00000000 00000000 11110000
变成十六进制也就是0xf0
&之后,再把后面4位给删掉,删掉我们可以用右移>>>4
来排除

通俗方法:

1
2
3
4
5
6
7
8
9
private static int findBitRight(int number,int fromIndex,int toIndex) {
subListRangeCheck(fromIndex, toIndex,31);
int i = 1<<fromIndex;
int tag = 1;
while (tag++ <= (toIndex - fromIndex)){
i |= (i << 1);
}
return (number&i)>>>fromIndex;
}
1
2
3
4
5
6
7
8
9
private static void subListRangeCheck(int fromIndex, int toIndex,int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}

简易方法:

1
2
3
4
int get4to7(int number){
int number1=15&(number>>4);
return number1;
}

2、在一个全由字母组成的字符串中找到第一个只出现一次的字符并返回他的位置,没有则返回-1000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static int firstUniqChar(String s) {
Map<Character,Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
if (map.get(c) == null){
map.put(c,1);
}else{
map.put(c,map.get(c)+1);
}
}
for (int i = 0; i < s.toCharArray().length; i++) {
Character c = s.charAt(i);
if (map.get(c) == 1){
return i;
}
}
return -1000;
}