Java 找出数字中的最高位和第二高位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19977353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:01:48  来源:igfitidea点击:

find highest and 2nd highest digit in a number

java

提问by user2991964

After finding the highest digit in a number,how to find the 2nd highest digit in that same number using only loops and if statements?

找到数字中的最高数字后,如何仅使用循环和 if 语句在同一数字中找到第二大数字?

    public static int maximum(int max){

while(num != 0){
            int rightDigit = num % 10;
            num /= 10;
            if(rightDigit > max)
                rightDigit = max;
        }
        return max;
        }

回答by LionC

Use a Listto store all digits and sortit, that way you have access to the highest, second highest to lowest digit as you wish. To sort a Listuse Collections.sort(List list)

使用 aList存储所有数字和sort它,这样您就可以根据需要访问最高、次高到最低的数字。排序List使用Collections.sort(List list)

回答by Paul Samsotha

int largest = 0;
int secondLargest = 0;

public static void minAndMax(int n){

    int num = n;
    int currentNum = 0;

    while(num % 10 != 0){
        currentNum = num % 10;

        if(currentNum > secondLargest) {
            secondLargest = currentNum;
        }
        if(secondLargest > largest) {
            largest = secondLargest;  
        }
        num /= 10; 
    }
}

回答by knordbo

Is this what you want? first element in array is largest, second element is second largest. Returns -1 if no such element.

这是你想要的吗?数组中的第一个元素是最大的,第二个元素是第二大的。如果没有这样的元素,则返回 -1。

public static void main(String[] args) {
    int[] tab = maximum(12);
    System.out.println("Largest digit: " + tab[0]);
    System.out.println("Second largest digit: " + tab[1]);
}
public static int[] maximum(int max){
    int num = max;
    int largest = -1;
    int secondLargest = -1;
    while(num != 0){
        int rightDigit = num % 10;
        num /= 10;

        if(rightDigit > largest) {
            secondLargest = Math.max(secondLargest, largest);
            largest = rightDigit;

        } else if(rightDigit > secondLargest)
            secondLargest = rightDigit;
    }
    return new int[]{largest,secondLargest};
    }

回答by Sumit Singh

public int secondMax(int number){
  List<Integer> list= new ArrayList<Integer>();
  while (number > 0) {
      list.add( number % 10 );
      number = number / 10;
  }

  Collections.sort(list);
  int size= list.size();   
  return list.get(size - 2);
}

回答by Kalai.G

Assume maxValue is the highest one and you can easily identify the second highest

假设 maxValue 是最高的,您可以轻松识别第二高

   if (times[i] > maxValue) {
        secondhighest  = maxValue;
        maxValue = times[i];
    } else if (times[i] > secondhighest) {
        secondhighest  = times[i];
    }

回答by Alexey Odintsov

int num = 1395248, n, i, n2;
for (n2 = i = n = 0; num > 0; i = num % 10, n2 = n < i ? n : n2, n = n < i ? i : n, num /= 10);
System.out.println(n);
System.out.println(n2);

回答by aga

Sorting the list of number's digits and getting the 1st and 2nd biggest digits will give you at best O(n * log n)time complexity (assuming you will use Quick Sort).
You can achieve somewhat better performance if you will use another approach: partition (reorder) your array (as in quick sort), so you'll have a pivot value which divides your array in two parts: those which are less than pivot are in the left part (left sub-array), those which are bigger are in the right part (right sub-array). Check the index of the pivot:

对数字的数字列表进行排序并获得第一个和第二个最大的数字将为您提供最佳O(n * log n)时间复杂度(假设您将使用Quick Sort)。
如果您使用另一种方法,您可以获得更好的性能:分区(重新排序)您的数组(如快速排序),因此您将有一个枢轴值将数组分为两部分:小于枢轴的那些在左侧部分(左子阵列),较大的部分位于右侧部分(右侧子阵列)。检查枢轴的索引:

  • if it's equal to the size of an array of digits minus 2, than it's the second biggest element (the first biggest is next to it, in the right sub-array);
  • if the index of pivot is less than size of an array of digits minus 2, repeat the partitioning for the right sub-array;
  • if the index of pivot is bigger than size of an array of digits minus 2, repeat the partitioning for the left sub-array;
  • 如果它等于数字数组的大小减 2,则它是第二大元素(第一大元素在它旁边,在右子数组中);
  • 如果pivot的索引小于数字数组的大小减2,则对右子数组重复分区;
  • 如果pivot的索引大于数字数组的大小减2,则对左子数组重复分区;

At some point your pivot will be the the second element from the end of an array, which means that it's the second biggest element, and the biggest number is in the end of an array (because of the way you get the pivot). The time complexity will be better than for a quick sort, because after each partition you're partitioning only one sub-array, not both of them.

在某些时候,您的枢轴将是数组末尾的第二个元素,这意味着它是第二大元素,而最大的数字位于数组的末尾(因为您获取枢轴的方式)。时间复杂度会比快速排序好,因为在每个分区之后,您只对一个子数组进行分区,而不是两个。

You can extend this approach to get not only the 1-st and 2-nd largest digits, but k-th (arbitrary highest) digit, and not only largest, but smallest also.

您可以扩展这种方法,不仅可以获得第 1 和第 2 大数字,还可以获得第 k(任意最高)数字,不仅是最大数字,而且是最小数字。

Check out the piece of code I've written couple of days ago:

看看我前几天写的一段代码:

public Long selectKthElement(int left, int right, int k, Type type) {
    int med = partitionIt(left, right);

    if ((type.equals(Type.Smallest) && med == k - 1) || (type.equals(Type.Largest) && med == nElems - k)) {
        return theArray[med];
    } else if (type.equals(Type.Smallest) && med > k || type.equals(Type.Largest) && med > nElems - k) {
        return selectKthElement(left, med - 1, k, type);
    } else if (type.equals(Type.Smallest) && med < k || type.equals(Type.Largest) && med < nElems - k){
        return selectKthElement(med + 1, right, k, type);
    } else {
        // impossible case, but the source code won't compile w/o the else
        return null;
    }
}

Here theArrayis an array of numbers' digits, partitionItmethod reorders an array and returns the index of median, you can either figure out how to write the implementation of it yourself, or search through the web.

theArray是一个数字的数字数组,partitionIt方法对数组重新排序并返回中位数的索引,您可以自己弄清楚如何编写它的实现,也可以通过网络搜索。

回答by Ulbo

U should do like this.

你应该这样做。

Hold two integer variables, highest and secondHighest do your while, and your first if-statement like the code u've shown add another if-statement which checks wether secondhighest is larger than digit AND wether secondhighest is smaller than highest

保存两个整数变量,highest 和 secondHighest 做你的 while,你的第一个 if 语句就像你展示的代码一样添加另一个 if 语句来检查 secondhighest 是否大于 digit 并且 secondhighest 是否小于 high

Hope this helps.

希望这可以帮助。

回答by saran3h

    public static int nthHighest(int[] arr, int n) {
         List<Integer> lst = Arrays.asList(ArrayUtils.toObject(arr)); //use apache commons library
         Collections.sort(lst);
         return lst.get(arr.length-n);
    }

回答by solanki dev

static void Main(string[] args)
{




    int max = 0, temp = 0, secondMax = 0, number = 0;

    number = 6541891;
    while (number != 0)
    {
        temp = number % 10;

        if (max == 0)
        {

            max = temp;
            secondMax = temp;

        }
        else if (temp > max)
        {
            int lastmax = max;

            max = temp;

            if (lastmax > secondMax)
            {
                secondMax = lastmax;
            }


        }

        if ((temp > secondMax && temp < max) || secondMax >= max)
        {
            secondMax = temp;
        }

        number = number / 10;
    }

    int Result = secondMax;

}