我如何检查数组中是否有任何整数的位数相同,例如24,54,67,如下面的例子所示

  • 本文关键字:例如 是否 数组 何检查 任何 整数 java
  • 更新时间 :
  • 英文 :

import java.util.Scanner;
public class BubbleInt {
public static void main(String [] args){
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter the total amount of number:);
int n = sc1.nextInt();
int [] missing = new int [n];
System.out.println("Please enter your numbers:");
for(int i=0; i<n; i++) {
missing[i] = sc1.nextInt();
}
//Sorting from largest to smallest
int temp = 0;
for(int i =0; i<missing.length; i++) {
for(int j =0; j<missing-1; j++) {
if(missing[i] > missing [j+1] {
temp = missing[j+1];
missing[j+1] = missing[i];
missing[i] = temp;
}
}
}
//Displaying 
for(int i = 0; i<missing.length; i++) {
System.out.println(missing[i] + " ");
}
}
}

我想把数组从大到小排序,上面的代码做得很好,但我想检查是否有两个相同位数的整数。例如,如果我输入77、23、5、1、7101,则输出应为101 23 77 1 5 7,因为1、5、7和23、77的位数相同,它们相反。我怎么能检查元素的长度是否相同,然后只反转它们呢。

要获得整数i>0的位数,请尝试以下操作:

var numDigits = ((int) Math.log10( i )) + 1;

交换循环内的条件可以更新为包括"位数",如下所示:

for( int i = 0; i < missing.length; i++ ) {
for( int j = 1; j < missing.length; j++ ) {
// Find the number of digits for ith and jth elements
int iDigits = ((int)Math.log10(missing[i]) + 1);
int jDigits = ((int)Math.log10(missing[j]) + 1);
// Perform a swap if iDigits > jDigits or ith element > jth element
if( (iDigits > jDigits) || (missing[i] > missing[j]) ) {
temp = missing[j];
missing[j] = missing[i];

Java 11解决方案:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class BubbleInt {
public static void main(String[] args) {
var sc1 = new Scanner(System.in);
System.out.println("Please enter the total amount of number:");
var n = sc1.nextInt();
var missing = new ArrayList<Integer>(n);
System.out.println("Please enter your numbers:");
while (missing.size() < n) {
missing.add(sc1.nextInt());
}
missing.stream()
.sorted(Comparator.comparing((Integer i) -> (int) Math.log10(i))
.reversed()
.thenComparing(Comparator.naturalOrder()))
.forEach(i -> System.out.println(i + " "));
}
}

相关内容

最新更新