如何按升序对数字进行排序,使零始终位于第2个位置而不使用数组。 [英] How do I sort the digits in ascending order such that zero always come in the 2nd position without using array.

查看:93
本文介绍了如何按升序对数字进行排序,使零始终位于第2个位置而不使用数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i

mport java.util.*;
public class sort1 {
	public static void main(String args[])
	{
		int num,sort=0;
		System.out.println("enter a no.\n");
		Scanner s=new Scanner(System.in);
		num=s.nextInt();
		for(int i=0;i<=9;i++)
		{
			int temp=num;
			while(temp>0)
			{
				int d=temp%10;
				
				if(d==i)
					sort=sort*10+d;
				
				temp=temp/10; 
				
			}
		}
		System.out.println(sort);
	}

}





我尝试过:



我正在尝试上面的代码,它工作正常,但它不包括零。我希望零作为第二位。



What I have tried:

i'm trying the above code which is working fine but it doesn't include zero.I want the zero as 2nd digit.

推荐答案

如果你的意思是我想在最低位数字位置,那么试试这个:

If you mean "I want a zero in the least significant digit position" then try this:
int digits = log10(num) + 2;
sort = 0;
int temp = num;
while (digits-- > 0)
    {
    int d = temp % 10;
    temp /= 10;
    sort = sort * 10 + d;
    }

如果你不这样做,那么你需要更详细地解释一下!

If you don't, then you will need to explain in a lot better detail!


有一个困难打印一个显着为零的数字,特别是因为您不知道数字中是否有零,并且您不知道它的长度。最简单的方法是将数字作为字符串读取,然后将其拆分为字符并按字母顺序对字符进行排序。
There is a difficulty in printing a number with one significant zero, especially as you do not know if there is a zero in the number to begin with, and you do not know its length. The easiest way to do this would be to read the number as a string and than split it into characters and sort the characters in alphabetic order.


这篇关于如何按升序对数字进行排序,使零始终位于第2个位置而不使用数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆