九度 1504 把数组排成最小的数

题目描述

 

总结

1. 将数字转化成 string 和字符串

sprintf(char*, "%d", int)

string = char*, 可以直接赋值

 

2. std::sort 的比较函数写法

bool cmp(const &int, const &int)

 

3. 能用库函数, 尽量用库函数, 能减少错误

 

代码未通过九度测试

#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;

int n;
int arr[1000];

bool cmp(const int &a, const int &b) {
	int cpa = a, cpb = b;
	int sizea = 0, sizeb = 0;
	while(cpa > 0) {
		cpa = cpa/10;
		sizea ++;
	}
	
	while(cpb > 0) {
		cpb = cpb/10;
		sizeb ++;
	}
	
	int newa = a * (pow(10, sizeb)) + b;
	int newb = b * (pow(10, sizea)) + a;
	
	return newa < newb;
}

int main() {
	freopen("C:\\Users\\vincent\\Dropbox\\workplacce\\joj\\test.txt", "r", stdin);
	while(scanf("%d", &n) != EOF) {
		for(int i = 0; i < n; i ++)
			scanf("%d", arr+i);
			
		sort(arr, arr+n, cmp);
		for(int i = 0; i < n; i ++)
			printf("%d", arr[i]);
		printf("\n");
	}
	return 0;
}

  

以前提交的代码, 通过九度测试

#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int numbers[200];
string str_num[200];

bool cmp(const string &str1, const string &str2) {
	string _str1 = str1;
	string _str2 = str2;
	_str1.append(str2);
	_str2.append(str1);

	return _str1 < _str2;

}

int main() {
	int n;
	while(scanf("%d", &n) != EOF) {
		for(int i = 0; i < n; i ++)
			scanf("%d", numbers+i);

		for(int i = 0; i < n; i ++) {
			char str[20];
			sprintf(str, "%d", numbers[i]);
			str_num[i] = str;
		}

		sort(str_num, str_num+n, cmp);

		for(int i = 0; i < n; i ++) {
			cout << str_num[i];
		}
		cout << endl;
	}
	return 0;
}

  

posted @ 2014-04-03 09:26  周卓  阅读(172)  评论(0编辑  收藏  举报