最大数的构成算法优化

boyle0630 2008-03-04 09:48:40
题目的意思是说输入一个数如48318,那么输出它的最大数即88431
我现在的算法是:
static int makemax(int n)
{
string[] numstr = new string[Convert.ToString(n).Length];
string num = "";
for (int i = 0; i <= Convert.ToString(n).Length - 1; i++)
{
numstr[i] = (Convert.ToString(n)[i]).ToString();
}
Array.Sort(numstr);
Array.Reverse(numstr);
for (int i = 0; i <= Convert.ToString(n).Length - 1; i++)
{
num += numstr[i];
}
return Convert.ToInt32(num);
}
但总感觉这种方法效率很低,请教优化的方法
...全文
100 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
boyle0630 2008-03-04
  • 打赏
  • 举报
回复
终于看到了,谢谢回复,下班前结贴
boyle0630 2008-03-04
  • 打赏
  • 举报
回复
这么垃圾的网站,明明有回复可怎么就是看不到
tnt1980 2008-03-04
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20070402/14/bd43984a-b844-487b-9b3f-3960b847450d.html

很好,很强大
vwxyzh 2008-03-04
  • 打赏
  • 举报
回复
        static int makemax(int value)
{
// 排除负数的情况
if (value < 0)
throw new ArgumentOutOfRangeException("value");
// 一共才1位,直接返回
if (value < 10)
return value;
// value的最大值是2G-1,也就是最多10位数
int[] buf = new int[10];
int count = 0;
while (value>0)
{
buf[count++] = value % 10;
value /= 10;
}
Array.Sort(buf, 0, count);
int result = 0;
for (int i = count - 1; i >= 0; i--)
{
checked //可能会溢出,例如输入1111111119
{
result *= 10;
result += buf[i];
}
}
return result;
}

harryheart 2008-03-04
  • 打赏
  • 举报
回复
...从语法上给点优化,不过装箱拆箱太多,还是没什么效率

static int Makemax(int n)
{
int result = 0;
char[] nums = n.ToString().ToCharArray();
Array.Sort(nums);
for (int i = nums.Length-1; i >=0; i--)
{
result = result * 10 +int.Parse( nums[i].ToString());
}
return result;
}
boyle0630 2008-03-04
  • 打赏
  • 举报
回复
应该还有更有效的算法啊,

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧