随便学(一)

二分搜索

  • 要求是排好序的数组中查找
  • 注意当hi,lo较大的时候,因为hi+lo有可能溢出,所以不用(hi+lo)/2

递归

int rank1(int key,int a[],int lo,int hi){
    if(lo>hi)
        return -1;
    int mid=lo+(hi-lo)/2;
    if(a[mid]<key)
        return rank(key,a,mid+1,hi);
    else if(a[mid]>key)
        return rank(key,a,lo,mid-1);
    else return mid;
}

非递归

int rank2(int key,int a[],int lo,int hi){
    while(lo<=hi){
        int mid=lo+(hi-lo)/2;
        if(a[mid]<key){
            lo=mid+1;
        }
        else if(a[mid]>key){
            hi=mid-1;
        }
        else return mid;
    }
    return -1;
}

Dijkstra双栈算术表达式求值

写法很鸡肋,意思明白就好
C++

#include <bits/stdc++.h>

using namespace std;

stack<int> num;
stack<char> opt;

bool checks(string s){
    bool f=true;
    for(int j=s.length()-1;j>=0;j--){
        if(s[j]>'9'||s[j]<'0'){
            f=false;
            break;
        }
    }
    return f;
}

int ti(string s){
    int temp=0;
    int ct=1;
    for(int j=s.length()-1;j>=0;j--){
        int n=(int)(s[j]-'0');
        temp+=ct*n;
        ct*=10;
    }
    return temp;
}

int getval(){
    string s;
    int con=0;
    while(cin>>s){
        if(checks(s))
            num.push(ti(s));
        else if(s=="*")
            opt.push(s[0]);
        else if(s=="+")
            opt.push(s[0]);
        else if(s=="-")
            opt.push(s[0]);
        else if(s=="(")
            con++;
        else if(s==")"){
            con--;
            char o=opt.top();
            opt.pop();
            int n1,n2,n3;
            n1=num.top();
            num.pop();
            n2=num.top();
            num.pop();

            cout<<"n1:"<<n1<<endl<<"n2:"<<n2<<endl;

            if(o=='*'){
                n3=n1*n2;
            }else if(o=='+'){
                n3=n2+n1;
            }else if(o=='-'){
                n3=n2-n1;
            }
            cout<<n3<<endl<<endl;
            if(con!=0)
                num.push(n3);
            else return n3;
        }
    }
}

int main()
{
    cout<<getval();
    return 0;
}

Java

在这里插入代码片

只有string,并且用cin才可以将字符串与字符串常量==

    string s;
    while(cin>>s){
        if(s=="af")
            cout<<s;
    }

下面是错的

    char s[10];
    while(~scanf("%s",s)){
        if(s=="af")
            cout<<s;
    }

另外,应该是pow计算的有浮点误差,以下的string转int是不对的
关于string转int,C++11有标准函数,但是C++11之前就得自己写

int ti(string s){
    int temp=0;
    int i=0;
    while(s[i]!='\0'){
        int n=int(s[i]-'0');
        cout<<n<<endl;
        cout<<pow(10,(s.length()-1-i))<<endl;

        temp=temp+n*pow(10,(s.length()-1-i));
        cout<<temp<<endl;
        i++;
    }
    cout<<temp;
    retur
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值