博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[华为机试练习题]29.Arrange an Array to Form a Smallest Digit
阅读量:6910 次
发布时间:2019-06-27

本文共 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/

你可能感兴趣的文章
Python [3] optparse、sys、hashlib模块
查看>>
等待事件之Log File Sync
查看>>
DML并行度限制
查看>>
python mix-in
查看>>
oracle的启动和关闭
查看>>
Docker 基础技术:Linux Namespace(下)
查看>>
VMwareWorkstation 15 木有響應 我勒個去……硬盤智障?
查看>>
如何用好 Google 等搜索引擎
查看>>
【QQ和新浪微博登陆第三方的简单实现】
查看>>
一文看尽HashMap
查看>>
预防XSS***
查看>>
神奇的scanf
查看>>
iptable
查看>>
[python的奇葩事]文件名不能与模块名同名
查看>>
删除win7多余引导项
查看>>
[李景山php]每天TP5-20170104|thinkphp5-File.php-1
查看>>
ehcache作为分布式缓存的研究
查看>>
Mysql for windows (MySQL开发)
查看>>
php测试kafka
查看>>
js获取两个日期之间时间差(天数)
查看>>