本文共 2184 字,大约阅读时间需要 7 分钟。
题目
描述: Question:
Input an array of positive integers, arrange the integers to form new digits, and output the smallest digit among all the new ones. Input Example 1: {2, 1}Output Example 1:12Input Example 2:{32, 321}Output Example 2:32132Input Example 3:{4589, 101,41425,9999}Output Example 3:1014142545899999;Interface: int smallestDigit(int a[],int nCount,char * strRst)Function: Arrange digits in the input array to form a smallest digit. Input: int a[]: an array of integersint nCount: length of the arraychar * strRst: returned valueOutput: noneReturn: o indicates success and -1 indicates exception.
练习阶段:
中级
代码
/*---------------------------------------* 日期:2015-07-01* 作者:SJF0115* 题目:Arrange an Array to Form a Smallest Digit * 来源:华为机试练习题-----------------------------------------*/#include#include #include #include "oj.h"#include using namespace std;#define MAX 10char* stra = new char[2*MAX+1];char* strb = new char[2*MAX+1];/**C++标准库的sort算法的第三个参数是一个 < 判断,当使用自定义函数时,此函数的返回类型是bool类型,第一个参数小于第二个参数时返回真,否则返回假。C中的qsort的第4个参数是一个返回值类型为int的函数,如果第一个参数小于第二个参数,返回负数;如果二者相等,返回0;否则返回正数。C/C++中整数0表示假,非0(包括正数和负数)表示真。不要混淆二者的使用方法,strcmp是一个C风格的比较函数,若要在sort中使用,需要包装成://参数类型修改为你要排序的数据的类型bool cmp(char*a,char*b){ return strcmp(a,b)<0;}**/bool cmp(char* str1,char* str2){ strcpy(stra,str1); strcat(stra,str2); strcpy(strb,str2); strcat(strb,str1); return strcmp(stra,strb) < 0;}// 功能:将输入的数组排成最小的数// 输入: int a[]:整型数组// int nCount:数组长度// char * strRst 返回值// 输出:// 返回:成功返回0 异常返回-1int smallestDigit(int a[],int nCount,char * strRst){ if(a == NULL || nCount <= 0 || strRst == NULL){ return -1; }//if // 整型转换为字符 char** strNumbers = (char**) (new char [nCount+1]); for(int i = 0;i < nCount;++i){ strNumbers[i] = new char[10]; sprintf(strNumbers[i],"%d",a[i]); }//for // 排序 sort(strNumbers,strNumbers+nCount,cmp); //输出 int index = 0; for(int i = 0;i < nCount;++i){ int size = strlen(strNumbers[i]); for(int j = 0;j < size;++j){ strRst[index++] = strNumbers[i][j]; }//for }//for strRst[index] = '\0'; return 1;}
转载地址:http://xobcl.baihongyu.com/