您的位置:首页 > 编程语言 > Go语言

两道算法问题

2017-08-30 16:25 134 查看
前两天看到一篇文章“优秀的程序员10分钟内能搞定下面5个编程问题,你呢?”,

把第4题和第5题做了一下。感觉第5题要在短时间内用C/C++写出bug-free的代码还是不容易,当然,如果用脚本语言可能会比较快。

第4题:

编写一个能将给定非负整数列表中的数字排列成最大数字的函数。例如,给定[50,2,1,9],最大数字为95021。

#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>

using namespace std;
int p[] = {50, 2, 21, 1, 19};

int compare (const void * a, const void * b)
{
string str_a, str_b;
stringstream stream_a, stream_b;

stream_a << *(int *)a;
stream_a >> str_a;
stream_b << *(int *)b;
stream_b >> str_b;

unsigned int i=0;
unsigned int len = min(str_a.length(), str_b.length());
while (i<len) {
if  (str_a[i] > str_b[i])
return 1;
else if (str_a[i] < str_b[i])
return -1;
else {
if (i==(str_a.length()-1)) {
if (str_b[i+1]>str_a[i])
return -1;
else
return 1;
}
else if (i==(str_b.length()-1)) {
if (str_a[i+1]>str_b[i])
return 1;
else
return -1;
}

i++;
}
}

return 0;
}

int main ()
{
int n;
qsort (p, sizeof(p)/sizeof(p[0]), sizeof(int), compare);
for (n=4; n>=0; n--)
printf ("%d ",p
);
return 0;
}


第5题:

编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。

#include <iostream>
using namespace std;

int p[9] = {1,2,3,4,5,6,7,8,9};
char o[3] = {'+','-','_'};
char l[8] = {'_','_','_','_','_','_','_','_'};

int num_list[9] = {0};
char opt_list[9] = {'#','#','#','#','#','#','#','#','#'};
int good_num=0;

void print_array() {
for (unsigned int i=0; (num_list[i]!=0); i++) {
cout<<num_list[i]<<" ";
cout<<opt_list[i]<<" ";
}
cout<<endl;
}

void preprocessing()
{
int i=0;
int num2=0;
int cur=0;

num2=p[0];
while (i<8) {

if ((l[i]=='+') || (l[i]=='-')) {
if ((cur==0) && (i==0)) {
num_list[cur] = p[i];
opt_list[cur] = l[i];
num2 = p[i+1];
}
else {
if ((l[i-1]=='+') || (l[i-1]=='-')) {
num_list[cur]=num2;
opt_list[cur]=l[i];
}
else {
num_list[cur]=num2+p[i];
opt_list[cur]=l[i];
}
num2=p[i+1];

if (i==7)
num_list[cur+1]=num2;
}
cur++;
}
else {
num2 = num2*10;
if ((i<7) && (l[i+1]=='_')) {
num2+=p[i+1];
}
if (i==7){
num2+=p[i+1];
num_list[cur]=num2;
}
}
i++;
}
}

int eval() {
unsigned int i;
preprocessing();
int result = num_list[0];
for (i=1; (num_list[i]!=0); i++) {
if (opt_list[i-1]=='+') {
result+=num_list[i];
}
else if (opt_list[i-1]=='-') {
result-=num_list[i];
}

}
return result;
}

void search(int cur) {
if (cur==8) {
for (int i=0; i<9; i++) {
num_list[i] = 0;
opt_list[i]='#';
}

if (eval() == 100) {
good_num++;
print_array();
}
}
else {
for (int j=0; j<3; j++) {
l[cur]=o[j];
search(cur+1);
}
}

}

int main()
{
search(0);
cout<<"good_num="<<good_num<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm-design