您的位置:首页 > 编程语言 > C语言/C++

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

2014-06-14 21:56 796 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: