100題 68

68題

輸入一個正整數數組,將它們連接起來排成一個數,輸出能排出的所有數字中最小的

只要把相鄰兩個字符串進行連接,比較字符串大小。最後排序一下即可

用c++實現起來比java麻煩多了,int與string不能直接連接的,必須先把int轉化成string

c++11標準中提供了std:tostring方法

#include<iostream>
#include<algorithm>
#include<string>
#include <sstream>
using namespace std;


string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}
int compare (const void * a, const void * b)
{
	string s1=( ""+itos(*(int*)a)+itos(*(int*)b) );
	string s2=(""+itos(*(int*)b)+itos(*(int*)a) );
	if(s1>s2) return 1;
	else if(s1==s2) return 0;
	else return -1;
}

int main ()
{
  int n;
  int values[] = { 40, 10, 100, 90, 202, 25 };
  qsort (values, 6, sizeof(int), compare);
  string s="";
  for(int i=0;i<6;i++)
	  s+=itos(*(int*)(values+i));
  cout<<s;
  return 0;
}







發佈了165 篇原創文章 · 獲贊 8 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章