简体   繁体   English

查找字符串中的最高和最低数字?

[英]Finding the highest and lowest numbers in a string?

You are given a string of space separated numbers, and have to return the highest and lowest number.你得到一串空格分隔的数字,并且必须返回最高和最低的数字。 I'm trying to solve this problem without using Math.max() or Math.min() .我试图在不使用Math.max()Math.min()的情况下解决这个问题。

This is my code so far:到目前为止,这是我的代码:


function highAndLow(nums){  
  
  let arr = nums.split(' ');
  let maxNum = arr[0];
  let minNum = arr[0];
  
  for(let i=0; i < arr.length; i++) {
    if(arr[i] > maxNum) {
        maxNum = arr[i];
        console.log('Setting maxNum to '  + maxNum);
      }
    } 

    for(let i=0; i < arr.length; i++) {
      if(arr[i] < minNum) {
          minNum = arr[i];
          console.log('Setting minNum to '  + minNum);
       }  
    }
    const result = maxNum + " " + minNum;
    return result;
}

Expected: 542, -214 , instead got: 6, -214预期: 542, -214 ,得到: 6, -214

Why am I getting 6 instead of 542?为什么我得到 6 而不是 542?

The solution turns out to be easier than expected:解决方案比预期的要容易:

 function highAndLow(nums){
   var array = nums.split(' ');

  var num = array.map(item => parseFloat(item));
  var sortedArray = num.sort((a, b) =>  b -a );
  console.log(sortedArray);
  return sortedArray[0] + ', ' + sortedArray.reverse()[0]
 }

 var result = highAndLow('2 3 9 3 50 32');
 console.log(result);

In this example you don´t use neither Math.max or Math.min在此示例中,您既不使用 Math.max 也不使用 Math.min

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM