当前位置: 首页 > 编程日记 > 正文

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

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/

相关文章:

微信小程序在web-view页面做分享,并且把分享的参数传递给小程序

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 本demo实现的功能&#xff0c;微信小程序给h5传参&#xff0c;h5给小程序传参 实现代码&#xff1a; <!--index.wxml --><web-view src"https://xxx.xxx.cn/test1.html?us…

洛谷—— P1118 [USACO06FEB]数字三角形Backward Digit Su…

https://www.luogu.org/problem/show?pid1118#sub 题目描述 FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 < N < 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. T…

Centos和Redhat的区别和联系

网上看到的&#xff0c;转载给大家 CentOS与RedHat的关系&#xff1a; RedHat在发行的时候&#xff0c;有两种方式&#xff1a;二进制的发行方式以及源代码的发行方式。无论是哪一种发行方式&#xff0c;你都可以免费获得&#xff08;例如从网上下载&#xff09;&#xff0c;并…

矩阵专职_新的篇章开始了-我将以专职技术作家的身份加入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出版物上提交(…

转:【小作品】STM32无线WIFI视频小车制作剖析(下)

转载于&#xff1a;http://blog.csdn.net/u012819339/article/details/50654764 实体作品请参看优酷视频。 若以上链接点击无效请把该链接地址复制到浏览器地址栏 http://v.youku.com/v_show/id_XODYzODczNzQ4.html 说明&#xff1a; 该作品为arvik于2014年下半年在学校实验室做…

JS 缓存 设置临时缓存和长期缓存 sessionStorage localStorage

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 使用 Window sessionStorage 和 localStorage 属性 sessionStorage 用于临时保存同一窗口(或标签页)的数据&#xff0c;在关闭窗口或标签页之后将会删除这些数据 localStorage 缓存在浏览…

SQL中distinct的用法

在表中&#xff0c;可能会包含重复值。这并不成问题&#xff0c;不过&#xff0c;有时您也许希望仅仅列出不同&#xff08;distinct&#xff09;的值。关键词 distinct用于返回唯一不同的值。表A&#xff1a;示例1select distinct name from A 执行后结果如下&#xff1a;示例2…

brain.js 时间序列_免费的Brain JS课程学习JavaScript中的神经网络

brain.js 时间序列The last few years, machine learning has gone from a promising technology to something we’re surrounded with on a daily basis. And at the heart of many machine learning systems lies neural networks.在过去的几年中&#xff0c;机器学习已经从…

小白的Unity5之路(一)

Player移动: 1 public float speed 6f;2 Vector3 movement;3 Rigidbody playerRididbody;4 5 void FixedUpdate () {6 float h Input.GetAxisRaw("Horizontal");7 float v Input.GetAxisRaw("Vertical");8 Move(h, v); 9…

Splunk学习与实践

一、 Splunk公司与产品 美国Splunk公司&#xff0c;成立于2004年&#xff0c;2012年纳斯达克上市&#xff0c;第一家大数据上市公司&#xff0c;荣获众多奖项和殊荣。总部位于美国旧金山&#xff0c;伦敦为国际总部&#xff0c;香港设有亚太支持中心&#xff0c;上海设有海外第…

VUE v-if 和 v-for 的使用示例 VUE根据下标改变图片路径

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 v-if 和 v-else v-for <div class"" v-for"(item,index) in [1,1,1,1,1,1,1,1,1,1]"><img v-if"helpeds0" class"tou1" :style"{…

聊天软交互原理_来自不同城市的人们如何在freeCodeCamp聊天室中进行交互

聊天软交互原理by Dborah Mesquita由DborahMesquita 来自不同城市的人们如何在freeCodeCamp聊天室中进行交互 (How people from different cities interact in the freeCodeCamp chatrooms) 推理统计入门以及如何使用spaCy从文本中提取信息 (A primer on Inferential statisti…

使用微信的JS-SDK实现自定义分享到微信朋友圈

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 实现代码 <!DOCTYPE html> <html><head><meta name"viewport" content"widthdevice-width, initial-scale1.0, user-scalableno, minimum-scale1.0, …

[Unity3D]Unity3D连衣裙实现游戏开发系统

大家好&#xff0c;我是秦培。欢迎关注我的博客&#xff0c;我的博客地址blog.csdn.net/qinyuanpei。 不知从什么时候開始&#xff0c;国产RPG单机游戏開始出现换装&#xff0c;仙剑系列中第一部实现了换装的游戏是仙剑奇侠传四&#xff0c;后来原上海软星团队。眼下的烛龙科技…

python中nlp的库_单词袋简介以及如何在Python for NLP中对其进行编码

python中nlp的库by Praveen Dubey通过Praveen Dubey 单词词汇入门以及如何在Python中为NLP 编写代码的简介 (An introduction to Bag of Words and how to code it in Python for NLP) Bag of Words (BOW) is a method to extract features from text documents. These featur…

机器学习:计算学习理论

计算学习理论介绍 关键词&#xff1a; 鲁棒性 关键词&#xff1a; 【机器学习基础】理解为什么机器可以学习1——PAC学习模型--简书 关键词&#xff1a;存在必要性&#xff1b;从机器学习角度出发 PAC学习理论&#xff1a;机器学习那些事 关键词&#xff1a;不错的大道理 如果相…

HTML超出部分滚动效果 HTML滚动 HTML下拉 附效果图

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 H5 效果图 实现代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>Bootstrap 实例 - 滚动监听&#xff08;Scrollspy&#xff09;…

编写高质量代码改善C#程序的157个建议——建议148:不重复代码

建议148&#xff1a;不重复代码 如果发现重复的代码&#xff0c;则意味着我们需要整顿一下&#xff0c;在继续前进。 重复的代码让我们的软件行为不一致。举例来说&#xff0c;如果存在两处相同的加密代码。结果在某一天&#xff0c;我们发现加密代码有个小Bug&#xff0c;然后…

求职者提问的问题面试官不会_如何通过三个简单的问题就不会陷入求职困境

求职者提问的问题面试官不会by DJ Chung由DJ Chung 如何通过三个简单的问题就不会陷入求职困境 (How to get un-stuck in your job search with three simple questions) 您甚至不知道为什么会被卡住&#xff1f; (Do you even know why you’re stuck?) Your job search can…

不能交换到解决jenkins用户的问题

su - jenkins始终有效&#xff0c;今centos无效&#xff0c;因为/etc/password在文档/bin/bash是yum当安装到/bin/false.之后可以改变。ubuntu安装包和yum安装包的行为不一致啊。版权声明&#xff1a;本文博主原创文章&#xff0c;博客&#xff0c;未经同意&#xff0c;不得转载…

HTML引用公共组件

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 在test.html引用footer.html 效果图 代码 test.html <!DOCTYPE html> <html><head><meta charset"utf-8"><title>引用demo</title><s…

Hadoop自学笔记(二)HDFS简单介绍

1. HDFS Architecture 一种Master-Slave结构。包括Name Node, Secondary Name Node,Data Node Job Tracker, Task Tracker。JobTrackers: 控制全部的Task Trackers 。这两个Tracker将会在MapReduce课程里面具体介绍。以下具体说明HDFS的结构及其功能。 Name Node:控制全部的Dat…

如何为Linux设置Docker和Windows子系统:爱情故事。 ?

Do you sometimes feel you’re a beautiful princess turned by an evil wizard into a frog? Like you don’t belong? I do. I’m a UNIX guy scared to leave the cozy command line. My terminal is my castle. But there are times when I’m forced to use Microsoft …

再谈Spring Boot中的乱码和编码问题

编码算不上一个大问题&#xff0c;即使你什么都不管&#xff0c;也有很大的可能你不会遇到任何问题&#xff0c;因为大部分框架都有默认的编码配置&#xff0c;有很多是UTF-8&#xff0c;那么遇到中文乱码的机会很低&#xff0c;所以很多人也忽视了。 Spring系列产品大量运用在…

UDP 构建p2p打洞过程的实现原理(持续更新)

UDP 构建p2p打洞过程的实现原理(持续更新) 发表于7个月前(2015-01-19 10:55) 阅读&#xff08;433&#xff09; | 评论&#xff08;0&#xff09; 8人收藏此文章, 我要收藏赞08月22日珠海 OSC 源创会正在报名&#xff0c;送机械键盘和开源无码内裤 摘要 UDP 构建p2p打洞过程…

Vue父组件网络请求回数据后再给子组件传值demo示例

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 这里demo使用延迟执行模拟网络请求&#xff1b;父组件给子组件需要使用自定义属性 Prop &#xff0c;下面是示例代码&#xff1a; <!DOCTYPE html> <html> <head> <me…

gulp-sass_如果您是初学者,如何使用命令行设置Gulp-sass

gulp-sassby Simeon Bello通过Simeon Bello I intern at a tech firm presently, and few days ago I got a challenge from my boss about writing an article. So I decided to write something on Gulp-sass. Setting it up can be frustrating sometimes, especially when…

MyEclipse快捷键

MyEclipse快捷键 Ctrl1 快速修复CtrlD: 删除当前行 CtrlQ 定位到最后编辑的地方 CtrlL 定位在某行 CtrlO 快速显示 OutLine CtrlT 快速显示当前类的继承结构 CtrlW 关闭当前Editer CtrlK 快速定位到下一个 CtrlE 快速显示当前Editer的下拉列表CtrlJ 正向增量查找(按下C…

关于UNION和UNION ALL的区别

今天在运行程序的时候发现个问题&#xff0c;就是计算和的时候两条数据一样的话自动去除重复的&#xff0c;可是我这个程序需要重复的数据也算进来呀&#xff0c;然后就找原因&#xff0c;最后在sql语句中找到了是union和union all的问题&#xff0c;简单总结一下下。 当使用到…

html 写一个日志控件 查看log

QQ技术交流群 173683866 526474645 欢迎加入交流讨论&#xff0c;打广告的一律飞机票 使用场景&#xff0c; 示例访问&#xff1a;https://weixin.njkeren.cn/test1.html?user12 得到的效果图 实现代码 <!DOCTYPE html> <html><head><meta charset&q…