小米二面题:
给定一个无符号数n,求二进制表示中1的个数。
版本1:
每次与1与,每次右移一位。
class Solution {
public:
int count1(unsigned n) {
int count = 0;
while (n>0)
{
if (n & 1) count++;
n >>= 1;
}
return count;
}
};
版本2:更快
每次与n-1与,每次消除一个1
class Solution {
public:
int count1(unsigned n) {
int count;
for (count = 0;n; count++)
{
n = n&(n - 1);
}
return count;
}
};
题2:求一个字符串中最长的连续子串这个可以用两个指针,一个i从到到尾,另一个j从i+1到尾,找到第一个与i相同的字符,然后下个相同则加1,再和之前的最长的数字进行比较,如果比之前的大则记录i的起始位数和最大长度,然候j继续向后,直到空,不过复杂度是n2。
其他的关于最长子串的可以参考这个博客最大子序列
class Solution {
public:
string substring(string s) {
int maxcount = 0;
int maxpos = 0;
int count = 0;
string res;
for (int i = 0; i < s.size(); i++)
{
for (int j = i+1; j < s.size(); j++)
{
if (s[j]==s[i])
{
count = 0;
while (s[i] == s[j])
{
count++;
i++;
j++;
}
if (count > maxcount)
{
maxcount = count;
maxpos = i-count;
i = i - count;//i要回到之前的位置
}
}
}
}
for (int i = maxpos; i <maxpos+maxcount; i++)
{
res.push_back(s[i]);
}
return res;
}
};