第一题:
汽水瓶换汽水
#include<bits/stdc++.h>
using namespace std;
int res=0;
int main(){
int bottle=0;
int drink=0;
while(cin>>bottle){
if(bottle==0)
break;
drink=0;
while(bottle>=3){
if(bottle==4){
drink+=2;
bottle=0;
}
drink+=bottle/3;
bottle=bottle/3+bottle%3;
}
if(bottle==2)
drink+=1;
cout<<drink<<endl;
}
return 0;
}
其实有更简单方法,f(n-2)+1,2个空瓶子换一瓶,即n/2
第二题:
N个随机数,不重复排序
#include<bits/stdc++.h>
using namespace std;
int main(){
int n=0;
cin>>n;
unordered_set<int> hashset;
vector<int> res;
int temp;
while(n>0){
n--;
cin>>temp;
if(hashset.find(temp)==hashset.end()){
hashset.emplace(temp);
res.push_back(temp);
}
}
sort(res.begin(),res.end());
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
return 0;
}
更简单方法,数组保存,然后用set,自动排序+去重
第三道:
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
数据范围:保证结果在 1<res<2^31-1
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin>>s;
int len=s.size();
long temp=1;
long res=0;
for(int i=len-1;i>=0;i--){
if(s[i]>='0' && s[i]<='9')
res+=temp*(s[i]-'0');
else if(s[i]>='A' && s[i]<='F')
res+=temp*(s[i]-'A'+10);
else
break;
temp*=16;
}
cout<<res;
return 0;
}