码迷,mamicode.com
首页 > 其他好文 > 详细

Arrange an Array to Form a Smallest Digit

时间:2015-01-10 15:17:15      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:华为入职练习 华为oj

#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include "oj.h"
using namespace std;

bool comp(int iElem1, int iElem2)
{
	string str1;
	char ch1[100];
	memset(ch1, 0, sizeof(char) * 100);
	itoa(iElem1, ch1, 10);
	str1 = ch1;

	string str2;
	char ch2[100];
	memset(ch2, 0, sizeof(char) * 100);
	itoa(iElem2, ch2, 10);
	str2 = ch2;

	int iCur1 = 0; //str1的下标
	int iCur2 = 0;//str2的下标

	int len1 = str1.length();
	int len2 = str2.length();

	while (iCur1 < len1 && iCur2 < len2)
	{
		if (str1[iCur1] < str2[iCur2])
		{
			return true;
		}
		else if(str1[iCur1] > str2[iCur2])
		{
			return false;
		}
		iCur1 ++;
		iCur2 ++;
	}
	if (iCur1 < len1)
	{
		while (iCur1 < len1)
		{
			iCur2 = (iCur2 + 1)% len2;
			if (str1[iCur1] < str2[iCur2])
			{
				return true;
			}
			else if(str1[iCur1] > str2[iCur2])
			{
				return false;
			}
			iCur1 ++;
		}
	}
	else if(iCur2 < len2)
	{
		while (iCur2 < len2)
		{
			iCur1 = (iCur1 + 1)% len1;
			if (str1[iCur1] < str2[iCur2])
			{
				return true;
			}
			else if(str1[iCur1] > str2[iCur2])
			{
				return false;
			}
			iCur2 ++;
		}
	}
	
	return false;

}


// 功能:将输入的数组排成最小的数
// 输入: int a[]:整型数组
//        int nCount:数组长度
//        char * strRst 返回值
// 输出:
// 返回:成功返回0  异常返回-1
int  smallestDigit(int a[],int nCount,char * strRst)
{
	if (NULL == a)
	{
		return -1;
	}
	sort(a, a + nCount , comp);
	char cTemp[100];
	
	for (int i = 0; i < nCount; ++i )
	{
		cout<<a[i]<<"	";
		memset(cTemp, 0, sizeof(char) * 100);
		itoa(a[i], cTemp, 10);
		strcat(strRst, cTemp);
	}
	cout<<endl;
	return 1;
}

int main()
{
	int a[] = {1,2};
	char szRst[100]  = {0};
	char *strExpect = "12";
	smallestDigit(a,2,szRst);
	cout<<szRst<<endl;
	//CPPUNIT_ASSERT(0 == strcmp(szRst,strExpect));
	
	return 0;
}

Arrange an Array to Form a Smallest Digit

标签:华为入职练习 华为oj

原文地址:http://blog.csdn.net/xiaohanstu/article/details/42583193

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!