Bitwise AND of Numbers Range My Submissions Question
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4.
求两个给定的数之间的数两两相与之后的结果
其实只需要求出来这两个数的二进制形式,从第几位开始后都是相同的就行了
eg:
1000 1010
1000 0001
这两个数之间有很多数,但是他们高4位相同,第四位不同,也就是这两个数之间的所有数,第四位 必定会有0有1,相与之后后四位必定为全0
所以两个数不断右移,什么时候相同了,再左移回来就对了
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
int count=0;
while(m!=n){
m>>=1;
n>>=1;
count++;
}
return m<<count;
}
}
做完后发现bit manipulation只剩下了一题,于是就也做了下
Repeated DNA Sequences
*
**All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: “ACGAATTCCG”. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. For example,
Given s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”,
Return: [“AAAAACCCCC”, “CCCCCAAAAA”].*
**
开始用hashmap超时了···
后来看了别人用了set,思路很直白直接上代码
public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
Set seen = new HashSet();
Set repeat = new HashSet();
List<String> result = new ArrayList<String>();
for(int i=0;i<s.length()-9;i++){
String repeatSeq=s.substring(i,i+10);
if(!seen.add(repeatSeq)){
repeat.add(repeatSeq);
}
}
result.addAll(repeat);
return result;
}
}
还有用编码的,各种形式不一
有的是这样编码的
A:00 C:01 G:10 T:11
有的是看asc码,发现后3位不同等等等
总之,思路都是一致的,比如说是取后3位编码的
那么先凑够10个长度的字符串
然后每次左移3位,然后新来的 字符 & 7得到后三位 再或一下
这样每次这30bit就代表了10个字符,然后放进Map或者set里面就行了
public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
int key=0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
List<String> result = new ArrayList<String>();
for(int i=0;i<s.length();i++){
key=(key<<3)&0x3fffffff|s.charAt(i)&7;
if(i<9)
continue;
if(map.containsKey(key)==false){
map.put(key,1);
}else if(map.get(key)==1){
map.put(key,2);
result.add(s.substring(i-9,i+1));
}
}
return result;
}
}