[英]How to sort Integer digits in ascending order without Strings or Arrays?
我試圖在不使用字符串、arrays 或遞歸的情況下按升序對任意長度的 integer 的數字進行排序。
例子:
Input: 451467
Output: 144567
我已經想出了如何通過模除法獲得 integer 的每個數字:
int number = 4214;
while (number > 0) {
IO.println(number % 10);
number = number / 10;
}
但我不知道如何在沒有數組的情況下訂購數字。
不用擔心IO
class; 這是我們教授給我們的定制 class。
它是 4 行,基於帶有一點 java 8 香料的 while 循環的for
循環變體:
int number = 4214;
List<Integer> numbers = new LinkedList<>(); // a LinkedList is not backed by an array
for (int i = number; i > 0; i /= 10)
numbers.add(i % 10);
numbers.stream().sorted().forEach(System.out::println); // or for you forEach(IO::println)
實際上有一個非常簡單的算法,它只使用整數:
int number = 4214173;
int sorted = 0;
int digits = 10;
int sortedDigits = 1;
boolean first = true;
while (number > 0) {
int digit = number % 10;
if (!first) {
int tmp = sorted;
int toDivide = 1;
for (int i = 0; i < sortedDigits; i++) {
int tmpDigit = tmp % 10;
if (digit >= tmpDigit) {
sorted = sorted/toDivide*toDivide*10 + digit*toDivide + sorted % toDivide;
break;
} else if (i == sortedDigits-1) {
sorted = digit * digits + sorted;
}
tmp /= 10;
toDivide *= 10;
}
digits *= 10;
sortedDigits += 1;
} else {
sorted = digit;
}
first = false;
number = number / 10;
}
System.out.println(sorted);
它將打印出1123447
。 這個想法很簡單:
該版本的算法可以按降序按降序排序,您只需要更改條件即可。
另外,我建議您看一下所謂的Radix Sort ,這里的解決方案從基數排序中汲取了一些想法,我認為基數排序是該解決方案的一般情況。
如何在不使用數組、字符串或排序 api 的情況下對數字進行排序? 好吧,您可以通過以下簡單步驟對數字進行排序(如果閱讀過多,請查看下面的調試輸出以了解排序是如何完成的):
我在 main 方法和一個函數中提供了一個帶有兩個 while 循環的代碼。 該函數什么都不做,只是構建一個新的整數,不包括傳遞給的數字,例如我傳遞函數 451567 和 1,函數返回我 45567(以任何順序,沒關系)。 如果這個函數傳遞了 451567 和 5 ,那么它會找到兩個 5 位數字並將它們添加到存儲和返回沒有 5 位數字的數字(這避免了額外的處理)。
調試,要知道它如何對整數進行排序:
最后一位是 : 7 of number : 451567
子塊是 45156
子塊是 4515
子塊是 451
子塊為 45
子塊為 4
451567 中的小數位是 1
商店是:1
從 451567 中刪除 1
減少的數字是:76554
最后一位是 : 4 of number : 76554
子塊是 7655
子塊是 765
子塊是 76
子塊為 7
76554 中的小數位是 4
商店是:14
從 76554 中刪除 4
減少的數字是:5567
最后一位是 : 7 of number : 5567
子塊是 556
子塊為 55
子塊為 5
5567中的小數位是5
店鋪是:145
從 5567 中刪除 5
找到重復的最小數字 5。 店鋪是:145
重復的最小數字 5 添加到存儲。 更新的商店是:1455
減少數量為:76
最后一位是 : 6 的數字 : 76
子塊為 7
76中的小數位是6
店鋪是:14556
從 76 中刪除 6
減少數量為:7
最后一位是 : 7 的數字 : 7
7中的小數位是7
店鋪是:145567
從 7 中刪除 7
減少的數字是:0
451567的升序為145567
示例代碼如下:
//stores our sorted number
static int store = 0;
public static void main(String []args){
int number = 451567;
int original = number;
while (number > 0) {
//digit by digit - get last most digit
int digit = number % 10;
System.out.println("Last digit is : " + digit + " of number : " + number);
//get the whole number minus the last most digit
int temp = number / 10;
//loop through number minus the last digit to compare
while(temp > 0) {
System.out.println("Subchunk is " + temp);
//get the last digit of this sub-number
int t = temp % 10;
//compare and find the lowest
//for sorting descending change condition to t > digit
if(t < digit)
digit = t;
//divide the number and keep loop until the smallest is found
temp = temp / 10;
}
System.out.println("Smalled digit in " + number + " is " + digit);
//add the smallest digit to store
store = (store * 10) + digit;
System.out.println("Store is : " + store);
//we found the smallest digit, we will remove that from number and find the
//next smallest digit and keep doing this until we find all the smallest
//digit in sub chunks of number, and keep adding the smallest digits to
//store
number = getReducedNumber(number, digit);
}
System.out.println("Ascending order of " + original + " is " + store);
}
/*
* A simple method that constructs a new number, excluding the digit that was found
* to b e smallest and added to the store. The new number gets returned so that
* smallest digit in the returned new number be found.
*/
public static int getReducedNumber(int number, int digit) {
System.out.println("Remove " + digit + " from " + number);
int newNumber = 0;
//flag to make sure we do not exclude repeated digits, in case there is 44
boolean repeatFlag = false;
while(number > 0) {
int t = number % 10;
//assume in loop one we found 1 as smallest, then we will not add one to the new number at all
if(t != digit) {
newNumber = (newNumber * 10) + t;
} else if(t == digit) {
if(repeatFlag) {
System.out.println("Repeated min digit " + t + "found. Store is : " + store);
store = (store * 10) + t;
System.out.println("Repeated min digit " + t + "added to store. Updated store is : " + store);
//we found another value that is equal to digit, add it straight to store, it is
//guaranteed to be minimum
} else {
//skip the digit because its added to the store, in main method, set flag so
// if there is repeated digit then this method add them directly to store
repeatFlag = true;
}
}
number /= 10;
}
System.out.println("Reduced number is : " + newNumber);
return newNumber;
}
}
我假設您被允許使用散列。
public static void sortDigits(int x) {
Map<Integer, Integer> digitCounts = new HashMap<>();
while (x > 0) {
int digit = x % 10;
Integer currentCount = digitCounts.get(digit);
if (currentCount == null) {
currentCount = 0;
}
digitCounts.put(x % 10, currentCount + 1);
x = x / 10;
}
for (int i = 0; i < 10; i++) {
Integer count = digitCounts.get(i);
if (count == null) {
continue;
}
for (int j = 0; j < digitCounts.get(i); j++) {
System.out.print(i);
}
}
}
我的算法:
int ascending(int a)
{
int b = a;
int i = 1;
int length = (int)Math.log10(a) + 1; // getting the number of digits
for (int j = 0; j < length - 1; j++)
{
b = a;
i = 1;
while (b > 9)
{
int s = b % 10; // getting the last digit
int r = (b % 100) / 10; // getting the second last digit
if (s < r)
{
a = a + s * i * 10 - s * i - r * i * 10 + r * i; // switching the digits
}
b = a;
i = i * 10;
b = b / i; // removing the last digit from the number
}
}
return a;
}
這是簡單的解決方案:
public class SortDigits
{
public static void main(String[] args)
{
sortDigits(3413657);
}
public static void sortDigits(int num)
{
System.out.println("Number : " + num);
String number = Integer.toString(num);
int len = number.length(); // get length of the number
int[] digits = new int[len];
int i = 0;
while (num != 0)
{
int digit = num % 10;
digits[i++] = digit; // get all the digits
num = num / 10;
}
System.out.println("Digit before sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
sort(digits);
System.out.println("\nDigit After sorting: ");
for (int j : digits)
{
System.out.print(j + ",");
}
}
//simple bubble sort
public static void sort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] > arr[j])
{
int tmp = arr[j];
arr[j] = arr[i];
arr[i] = tmp;
}
}
}
}
由於數字中可能的元素(即數字)是已知的(0 到 9)並且很少(總共 10 個),您可以這樣做:
int number = 451467;
// the possible elements are known, 0 to 9
for (int i = 0; i <= 9; i++) {
int tempNumber = number;
while (tempNumber > 0) {
int digit = tempNumber % 10;
if (digit == i) {
IO.print(digit);
}
tempNumber = tempNumber / 10;
}
}
class SortDigits {
public static void main(String[] args) {
int inp=57437821;
int len=Integer.toString(inp).length();
int[] arr=new int[len];
for(int i=0;i<len;i++)
{
arr[i]=inp%10;
inp=inp/10;
}
Arrays.sort(arr);
int num=0;
for(int i=0;i<len;i++)
{
num=(num*10)+arr[i];
}
System.out.println(num);
}
}
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int length = 0;
long tem = 1;
while (tem <= n) {
length++;
tem *= 10;
}
int last=0;
int [] a=new int[length];
int i=0;
StringBuffer ans=new StringBuffer(4);
while(n!=0){
last=n%10;
a[i]=last;
n=n/10;
i++;
}
int l=a.length;
for(int j=0;j<l;j++){
for(int k=j;k<l;k++){
if(a[k]<a[j]){
int temp=a[k];
a[k]=a[j];
a[j]=temp;
}
}
}
for (int j :a) {
ans= ans.append(j);
}
int add=Integer.parseInt(ans.toString());
System.out.println(add);
對於輸入:
n=762941 ------->integer
我們得到輸出:
149267 ------->integer
import java.util.*;
class EZ
{
public static void main (String args [] )
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number - ");
int a=sc.nextInt();
int b=0;
for (int i=9;i>=0;i--)
{
int c=a;
while (c>0)
{
int d=c%10;
if (d==i)
{
b=(b*10)+d;
}
c/=10;
}
}
System.out.println(b);
}
}
import java.util.Scanner;
public class asc_digits
{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("number");
int n=in.nextInt();
int i, j, p, r;
for(i=0;i<10;i++)
{
p=n;
while(p!=0)
{
r = p%10;
if(r==i)
{
System.out.print(r);
}
p=p/10;
}
}
}
}
Stream 也可以用於此:
public static int sortDesc(final int num) {
List<Integer> collect = Arrays.stream(valueOf(num).chars()
.map(Character::getNumericValue).toArray()).boxed()
.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
return Integer.valueOf(collect.stream()
.map(i->Integer.toString(i)).collect(Collectors.joining()));
}
class HelloWorld {
public static String str="opppa";
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
System.out.println(" rever number is= "+reversernum(num));
System.out.println("\n sorted number is= "+sortedNumdesc(num));
}
private static int reversernum(int n1)
{
if(n1<10)
return n1;
int n_reverse=0;
int lastDigit=0;
while(n1>=1)
{
lastDigit=n1%10;
n_reverse=n_reverse*10+lastDigit;
// System.out.println(" n_reverse "+n_reverse);
n1=n1/10;
}
return n_reverse;
}
private static int sortedNumdesc(int num)
{
if(num<10)
return num;
List<Integer> numbers = new LinkedList<>();
for (int i=num ;i>0;i/=10)
numbers.add(i%10);
// numbers.stream().sorted().forEach(System.out:: println);
int sorted_Num=0;
List<Integer> sortednum= numbers.stream().sorted()
.collect(Collectors.toList());
// System.out.println("sorted list "+sortednum);
for(Integer x: sortednum)
sorted_Num=sorted_Num*10+x;
return sorted_Num;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.