如何从JavaScript中的给定数字中形成最小的数字

news/2024/7/3 2:47:53

by Prashant Yadav

通过Prashant Yadav

如何从JavaScript中的给定数字中形成最小的数字 (How to form the smallest possible number from a given number in JavaScript)

In this tutorial, we will implement an algorithm to form the smallest possible number with ES6.

在本教程中,我们将实现一种算法,以使用ES6形成尽可能小的数字。

Input: 55010 7652634
Output: 10055 2345667

Note: The transformed number should not start with 0 if it has at least one non-zero character.

注意 :如果转换后的数字至少包含一个非零字符,则不应以0开头。

We are going to use two different approaches to solve this problem. Everything will be written in ES6.

我们将使用两种不同的方法来解决此问题。 一切都将用ES6编写。

  • In the first approach, we will assume that the provided number is in string format and solve it using sorting which will take O(nlogn).

    在第一种方法中,我们将假定提供的数字为字符串格式,并使用将采用O(nlogn)的排序对其进行求解。
  • In the Second approach, we will solve with numeric value with O(d) time, where d is the number of digits.

    在第二种方法中,我们将使用O(d)时间的数值进行求解,其中d是位数。

使用排序O(nlogn)。 (Using sorting O(nlogn).)

实作 (Implementation)

  • We will convert the number to the character array and then sort that array.

    我们将数字转换为字符数组,然后对该数组进行排序。
  • After sorting we will check if the first character in the array is 0.

    排序后,我们将检查数组中的第一个字符是否为0。
  • If it is not 0 then we will join the array and return it.

    如果它不是0,那么我们将加入数组并返回它。
  • If it is 0 then we will find the first non-zero number and swap it with 0 and return it.

    如果它是0,那么我们将找到第一个非零数字并将其与0交换并返回。
function smallestPossibleNumber(num){
//Create a character array and sort it in ascending orderlet sorted = num.split('').sort();
//Check if first character is not 0 then join and return it if(sorted[0] != '0'){    return sorted.join('');}
//find the index of the first non - zero character let index = 0; for(let i = 0; i < sorted.length; i++){  if(sorted[i] > "0"){    index = i;    break;  } }
//Swap the indexes  let temp = sorted[0];  sorted[0] = sorted[index];  sorted[index] = temp;
//return the string after joining the characters of array return sorted.join(''); }

Running the Program

运行程序

Input:console.log(smallestPossibleNumber('55010'));console.log(smallestPossibleNumber('7652634'));console.log(smallestPossibleNumber('000001'));console.log(smallestPossibleNumber('000000'));
Output:100552345667100000000000
/*How it works  let sorted = num.split('').sort();   = ['5','5','0','1','0'].sort() = ['0','0','1','5','5']  if(sorted[0] != '0'){   // '0' != '0' condition fails     return sorted.join('');  }    //Find the index of the first non - zero character  let index = 0;  for(let i = 0; i < sorted.length; i++){     if(sorted[i] > '0'){  // '1' > '0'       index = i;      // index = 2;       break;          // break;     }  }    //swap the index  var temp = sorted[0];        sorted[0] = sorted[index];  sorted[index] = temp;    //return the string  return sorted.join('');*/

这个怎么运作 (How it works)

We first created the array of characters like ['5', '5', '0', '1', 0] . Then we sort this to['0', '0', '1', '5', '5'] After this, we find the first non-zero element and swap it with first zero elements like ['1', '0', '0', '5', '5'] . Now we have our smallest number ready we just need to concatenate them together and return it.

我们首先创建了一个字符数组,例如['5', '5', '0', '1', 0] 。 然后,将其排序为['0', '0', '1', '5', '5']之后,我们找到第一个非零元素并将其与诸如['1', '0', '0', '5', '5'] 。 现在我们已经准备好最小的数目,我们只需要将它们连接在一起并返回即可。

Learn more about the split(), sort(), join().

了解有关split() , sort() , join()的更多信息 。

Time Complexity: O(nlogn).Space Complexity: O(n).

时间复杂度:O(nlogn)。空间复杂度:O(n)。

时空复杂度说明 (Time and Space complexity explanation)

We are creating a character array which will take O(n) time. Then sorting the array will take O(nlogn).

我们正在创建一个需要O(n)时间的字符数组。 然后对数组排序将使用O(nlogn)。

After that, we are finding the index of smallest non zero number which can take O(n) in the worst case and joining the array to create the string will take O(n). As these all operations are running one after other. So time complexity is O(n + nlogn + n + n) = O(nlogn).

此后,我们找到最小的非零数字的索引,该索引在最坏的情况下可以采用O(n),并加入数组以创建字符串将采用O(n)。 由于所有这些操作都在一个接一个地运行。 因此,时间复杂度为O(n + nlogn + n + n)= O(nlogn)。

We are creating an array of characters from the string, so space complexity is O(n).

我们正在根据字符串创建字符数组,因此空间复杂度为O(n)。

使用数值O(logn)。 (Using numeric value O(logn).)

There is a drawback in this approach: if the number only contains zeros then it will return a single zero.

这种方法有一个缺点:如果数字仅包含零,则它将返回单个零。

实作 (Implementation)

  • We will create an array of numbers from 0 to 9.

    我们将创建一个从0到9的数字数组。
  • Then we will keep track of the digits present in the number by increasing their count in the array.

    然后,我们将通过增加数组中的数字来跟踪数字中存在的数字。
  • After that, we will find the smallest non-zero digit and decrease its count by 1.

    之后,我们将找到最小的非零数字并将其计数减少1。
  • In the end, we will recreate the number by arranging them in ascending order and return the result.

    最后,我们将按升序排列数字,然后返回结果。
  • This solution is based on the counting sort.

    该解决方案基于计数排序。
function smallestPossibleNumber(num) {    // initialize frequency of each digit to Zero   let freq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];          // count frequency of each digit in the number   while (num > 0){      let d = parseInt(num % 10); // extract last digit     freq[d]++; // increment counting     num = parseInt(num / 10); //remove last digit   }
// Set the LEFTMOST digit to minimum expect 0   let result = 0;    for (let i = 1 ; i <= 9 ; i++) {       if (freq[i] != 0) {          result = i;          freq[i]--;          break;      }    }           // arrange all remaining digits   // in ascending order   for (let i = 0 ; i <= 9 ; i++) {      while (freq[i]-- != 0){          result = result * 10 + i;       }   }        return result; }

Running the program

运行程序

Input:console.log(smallestPossibleNumber('55010'));console.log(smallestPossibleNumber('7652634'));console.log(smallestPossibleNumber('000001'));console.log(smallestPossibleNumber('000000'));
Output:10055234566710
/* How it works   // initialize frequency of each digit to Zero   let freq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];      // count frequency of each digit in the number   while (num > 0){      let d = parseInt(num % 10); // extract last digit     freq[d]++; // increment counting             num = parseInt(num / 10); //remove last digit   }    //After incrementing count   //freq = [2, 1, 0, 0, 0, 2, 0, 0, 0, 0]      // Set the LEFTMOST digit to minimum expect 0   let result = 0;    for (let i = 1 ; i <= 9 ; i++) {       if (freq[i] != 0) {          result = i;          freq[i]--;          break;      }    }    // result = 1     // arrange all remaining digits   // in ascending order   for (let i = 0 ; i <= 9 ; i++) {      while (freq[i]-- != 0){          result = result * 10 + i;       }   }
//10   //100   //1005   //10055   //10055      return result*/

Time Complexity: O(nlogn).Space Complexity: O(1).

时间复杂度:O(nlogn);空间复杂度:O(1)。

时空复杂度说明 (Time and Space complexity explanation)

We are removing each digit from the number and incrementing its respective count in an array that will take O(logn). Then we find the smallest non-zero number from the array in O(10).

我们正在从数字中删除每个数字,并在需要O(logn)的数组中增加其各自的计数。 然后我们从O(10)中的数组中找到最小的非零数。

After that we are rearranging the digits to create the smallest number in O(10 * logn). Time complexity is O(logn + 10+ 10logn) = O(logn) or O(d), where d is the no of digits

之后,我们将重新排列数字以在O(10 * logn)中创建最小的数字。 时间复杂度为O(logn + 10+ 10logn)= O(logn)或O(d),其中d为数字位数

We are using constant space (an array of 10 numbers), so space complexity is O(1).

我们使用的是恒定空间(由10个数字组成的数组),因此空间复杂度为O(1)。

If you liked this article, please give it some ?and share it! If you have any questions related to this feel free to ask me.

如果您喜欢这篇文章,请给它一些?并分享! 如果您对此有任何疑问,请随时问我。

For more like this and algorithmic solutions in Javascript, follow me on Twitter. I write about ES6, React, Nodejs, Data structures, and Algorithms on learnersbucket.com.

有关Java的更多此类信息和算法解决方案,请在 Twitter上 关注我 我写ES6 ,React过来,的NodeJS, 数据结构和算法上learnersbucket.com

翻译自: https://www.freecodecamp.org/news/forming-the-smallest-possible-number-from-the-given-number-in-javascript-bda790655c8e/


http://lihuaxi.xjx100.cn/news/238818.html

相关文章

ansible组件-playbook学习笔记

playbook的基础组件 name 定义playbook或者task的名称 hosts 用于指定要执行指定任务的主机 user 用于指定远程主机上的执行任务的用户 task 任务列表 vars 定义变量 vars_files 定义变量文件 notify 任务执行结果如果是发生更改的则触发定义在handler的任务 handlers 用于当前…

2018湖湘杯海选复赛Writeup

2018湖湘杯Writeup0x01 签到题0x02 MISC Flow0x03 WEB Code Check0x04 WEB Readflag0x05 WEB XmeO0x06 Reverse Replace0x07 MISC Disk0x08 Crypto Common Crypto0x09 Reverse HighwayHash640x10 Web Mynot0x01 签到题 关注合天智汇公众号&#xff0c;回复hxb2018得到flag。0x…

区块链技术简介

想知道更多区块链技术知识&#xff0c;请百度【链客区块链技术问答社区】链客&#xff0c;有问必答&#xff01;&#xff01;我最近看区块链简单介绍的时候会发现有的人就说其有良好的隐私性&#xff0c;但也有人说保护隐私性上有缺陷&#xff0c;今天就简单的对区块链的隐私做…

DELL RAID卡管理工具 MegaRAID Storage Manager(偏重RAID常用管理命令)

前言&#xff1a; 业务生产中大部分服务器RAID控制器使用的LSI产品&#xff0c;例如服务器&#xff1a;DELL、IBM、HP、浪潮、联想、华为。本文主要针对行业主流服务器DELL系列RAID卡管理&#xff0c;借住LSI产品管理软件MegaRAID Storage Manager &#xff08;以下简称MSM&…

矩阵专职_新的篇章开始了-我将以专职技术作家的身份加入RunCloud

矩阵专职If you used to submit (or read) articles on the freeCodeCamp Medium publication, there is a chance that your article may have been edited by me (or by another member of the team of volunteer editors).如果您以前曾经在freeCodeCamp Medium出版物上提交(…

vue:虚拟dom的实现

Vitual DOM是一种虚拟dom技术&#xff0c;本质上是基于javascript实现的&#xff0c;相对于dom对象&#xff0c;javascript对象更简单&#xff0c;处理速度更快&#xff0c;dom树的结构&#xff0c;属性信息都可以很容易的用javascript对象来表示&#xff1a; let element{tagN…

Mac MySQL配置环境变量的两种方法

第一种&#xff1a; 1.打开终端,输入&#xff1a; cd ~ 会进入~文件夹 2.然后输入&#xff1a;touch .bash_profile 回车执行后&#xff0c; 3.再输入&#xff1a;open -e .bash_profile 会在TextEdit中打开这个文件&#xff08;如果以前没有配置过环境变量&#xff0c;那么这…

再谈HOST文件

前几天弄了一个关于禁止打开某个网站的文章后&#xff0c;觉得这个HOST文件真的挺有意思的。并且也总是想把自己对它新的理解写下来&#xff08;也许大家都明白了&#xff09;以下是HOST文件的内容&#xff1a;# Copyright (c) 1993-1999 Microsoft Corp.## This is a sample H…