zoukankan      html  css  js  c++  java
  • 九度 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("
    ");
    	}
    	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;
    }
    

      

  • 相关阅读:
    sql 四大排名函数--简介
    Markdown语法规则
    利用ADO操作外部数据——Excel之VBA(15)
    VBA中的用户信息交换——Excel之VBA(14)
    窗体和控件(2)——Excel之VBA(13)
    窗体和控件(1)——Excel之VBA(12)
    使用VBA数组公式——Excel之VBA(11)
    使用DIR函数合并多个文件的数据——Excel之VBA(10)
    ubuntu jupter python虚拟环境
    Pytorch_加载自己的数据集并训练
  • 原文地址:https://www.cnblogs.com/zhouzhuo/p/3642198.html
Copyright © 2011-2022 走看看