Powered by:AB_IN 局外人
真的挺适合我这种小白的。
循环右移
记一下按权相加法
class Solution {
public:
long long rotateRight(string str, int k) {
// write code here
long long ans=0;
int n=str.size();
for(int i=n-k;i<n;i++){
ans=ans*2+(str[i]-'0');
}
for(int i=0;i<n-k;i++){
ans=ans*2+(str[i]-'0');
}
return ans;
}
};
如果想调用类,可以这样
Solution solution;
cout<<solution.rotateRight("01111",2);
牛牛的01游戏
一个栈的操作,先进后出。
注意的是调用类:
在我们定义函数和类的时候,在第一个参数的位置默认应该添加 ,例如 ,然后我们在调用的时候应该首先实例化这个类,如 ,而非直接调用 。
class Solution:
def solve(self , str ):
# write code here
lst=[str[0]]
for i in str[1:]:
if i=='0':
if lst and lst[-1]=='0':
lst.pop()
if lst and lst[-1]=='1':
lst.pop()
else:
lst.append("1")
else:
lst.append("0")
else:
if lst and lst[-1]=='1':
lst.pop()
else:
lst.append("1")
return "".join(lst)
print(Solution().solve("00110"))
牛牛爱奇数
用
去重并标记即可。
当然也可以用
标记。
class Solution:
def solve(self , n , a ):
s = set()
for i in a:
while i%2==0 and i not in s:
s.add(i)
i = i>>1
return len(s)
也可以用堆。
class Solution
{
public:
int solve(int n,vector<int> &a)
{
priority_queue<int> q;
int t=0;
for(int i=0;i<n;i++)
if(a[i]%2==0)
q.push(a[i]);
while(!q.empty())
{
int p=q.top();
while(q.top()==p&&!q.empty())
q.pop();
p/=2;
t++;
if(p%2==0) q.push(p);
}
return t;
}
};