一些算法的代码练习(c++实现,编译环境xcode)

1. 将excel表格的列转换成整数,例如a=1,b=2,。。。z=26,aa=27,。。。等等。

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main(int argc, const char * argv[])
{
    if (argc != 2) {
        cout<<"Input error!"<<endl;
        return -1;
    }
    string s(argv[1]);
    int sum = toupper(s[0]) - 'A' + 1;
    for (int i = 1; i < s.size(); i++) {
        sum = sum * 26 + (toupper(s[i]) - 'A' + 1);
    }
    cout<<sum<<endl;
    return 0;
}

2.字符串压缩,例如把xxxyyz变成3x2yz,返回压缩后新字符串string strzip(const string &str);//这个代码是胡总写的,真好

#include <iostream>
#include <string>
using namespace std;

string strzip(const string &str){
    string ret;
    for(auto it=str.begin();it!=str.end();){
        char c=*it;
        int count=0;
        while(it!=str.end()&&*it==c){
            count++;
            it++;
        }
        if(count!=1){
            ret.append(to_string(count));
        }
        ret.push_back(c);
    }
    return ret;
}

int main(int argc, const char * argv[])
{
    string str = "az";
    cout<<strzip(str)<<endl;
    return 0;
}

3.已排序整数数组,设计O(n)时间算法确定数组中是否存在两个数的和正好为x。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void sumup(const vector<int> &iv, const int x){
    for (auto itl = iv.begin(), itr = iv.end()-1; itl!=itr; ) {
        if (*itl+*itr>x) {
            --itr;
        }else if (*itl+*itr<x){
            ++itl;
        }else{
            cout<<x<<"="<<*itl<<"+"<<*itr<<endl;
            return;
        }
    }
    cout<<"Not found!"<<endl;
}

int main(int argc, const char * argv[])
{
    vector<int> iv;
    iv.push_back(1);
    iv.push_back(3);
    iv.push_back(6);
    iv.push_back(7);
    iv.push_back(10);
    sumup(iv, 10);
    return 0;
}

4.求斐波那契数列第n项,规定n不小于2,不能用循环,用函数递归,怎么样递归次数最少

#include <iostream>
#include <string>
#include <vector>
using namespace std;
//找出fibonacci第n个数,n不小于2
const int fibonacci(const int t,const int i, const int j){
    if (t==2) {
        return j;
    }
    return fibonacci(t-1,j,i+j);
}

int main(int argc, const char * argv[])
{
    cout<<fibonacci(8,1,1)<<endl;
    return 0;
}

5.http://www.cnblogs.com/bennettwang00/p/3598909.html

#include <iostream>
#include <cmath>
using namespace std;

void formatout(const int &n){
    if (n<1) {
        return;
    }
    int p = floor(log2(n));
    int i = 1;
    for (int j = 0; j<p; ++j) {
        for(int k = 0; k<pow(2, j); ++k){
            cout<<i++<<" ";
        }
        cout<<endl;
    }
    while (i<=n) {
        cout<<i++<<" ";
    }
    cout<<endl;
}

int main(int argc, const char * argv[])
{
    formatout(17);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值