90分钟,20道不定项+2道编程。
1、给定一个数组,将所有的奇数放在数组前半部分,偶数放在后半部分,奇数和奇数、偶数和偶数之间的相对位置不变。
思路:从后往前遍历,每次找到奇数时就插入到数组最前面,并删除掉该数。
//剑指Offer有原题,直接拿过来用了
class Solution {
public:
void reOrderArray(vector<int> &array) {
int n=1,count=1;
while(n<=array.size()){
if(array[array.size()-count]%2==1){
array.insert(array.begin(),array[array.size()-count]);
auto it=array.end()-1;
while(*it!=array[array.size()-count]) it--;
array.erase(it);
}
else count++;
n++;
}
}
};
2、输入一个四则运算表达式(包含括号),求表达式结果。
思路:这道题简!直!坑!它的函数原型是double func(char* str, int n),传入的是一个C风格字符串!也就是说首先你在处理时首先还得把相应字符数组转换成数字(还可能有小数),然后才能计算下一步结果!
讲真,单独给我一个半小时我都写不完这道题,深感自己能力不足,有点难过。。。
花了N久终于写完了,主要是时隔几天再来看代码,有些不认识了。。。
主要参考的文章是这篇,将中缀表达式转换成后缀表达式,并且由于有小数点的存在,代码的处理整体复杂了许多。
#include<iostream>
#include<stack>
#include<queue>
#include<iterator>
using namespace std;
double get_number(char* &p){
vector<int> vec;
vec.push_back(*p-'0');
*p++;
int left=1,temp=0;
double right=1,ans=0;
while(*p!='\0'&&*p>='0'&&*p<='9'){
left*=10;
vec.push_back(*p-'0');
*p++;
}
if(*p=='.'){
*p++;
while(*p>='0'&&*p<='9'){
right/=10;
vec.push_back(*p-'0');
*p++;
}
}
temp=vec.size()-1;
while(right!=1){
ans+=right*vec[temp--];
right*=10;
}
temp=0;
while(left>=1){
ans+=left*vec[temp++];
left/=10;
}
return ans;
}
int get_order(char* str){
switch(*str) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
double cal(double temp1,double temp2,char c){
switch(c){
case '+':
return temp1+temp2;
case '-':
return temp1-temp2;
case '*':
return temp1*temp2;
case '/':
return temp1/temp2;
}
}
double func(char *str,int n){
double ans=0,temp1,temp2;
stack<char> sc;
queue<double> qd;
queue<char> qc;
while(*str!='\0'){
if(*str=='+'||*str=='-'||*str=='*'||*str=='/'||*str=='('||*str==')'){
if(*str=='('){
sc.push(*str);
}
else if(*str==')'){
while(sc.top()!='('){
qc.push(sc.top());
sc.pop();
}
sc.pop();
}
else if(sc.empty()||(get_order(str)>get_order(&sc.top()))){
sc.push(*str);
}
else{
while(!sc.empty()&&sc.top()!='('&&(get_order(str)<=get_order(&sc.top()))){
qc.push(sc.top());
sc.pop();
}
sc.push(*str);
}
str++;
}
else{
qd.push(get_number(str));
qc.push('!');
}
}
while(!sc.empty()){
if(sc.top()!='('&&sc.top()!=')'){
qc.push(sc.top());
}
sc.pop();
}
stack<double> sd;
while(!qc.empty()){
if(qc.front()=='!'){
sd.push(qd.front());
qd.pop();
}
else{
double temp2=sd.top();
sd.pop();
double temp1=sd.top();
sd.pop();
sd.push(cal(temp1,temp2,qc.front()));
}
qc.pop();
}
return sd.top();
}
int main()
{
char str[]="(1.2+3)*((8.3-7.3)+10/2)";
cout<<func(str,sizeof(str))<<endl;
return 0;
}