关于math:Mathrandom的玩法

知识点1.Math.random() 随机数0.××××××× 2.toString() 将数字变成字符串, 不然substring辨认不了 3.substring(2, 4) 从第二个开始,到第四个完结(不算4) (0 1 2 3 4) 源码如下随机数变成字符串,而后再切割。最初包裹一个(),括号加一个+号就能悄悄的强制类型转换成数字。小于等于1就能中奖了 <div class="item"></div><script> var a = +(Math.random().toString().substring(2, 4)) var txt = document.querySelector(".item") if (a <= 1) { txt.innerHTML = "中奖了" txt.className = "item good" } else { txt.innerHTML = "未中奖" } console.log(typeof a, a)</script>.item { padding: 80px; background: rgb(0, 0, 0, 0.69) no-repeat; width: 400px; margin: 0 auto; color: #ffffff; text-align: end; border-radius: 10px; font-size: 35px; font-family: 微软雅黑; font-weight: bolder; background-image: url(https://img.zcool.cn/community/01e5ed5bbb4d7ba801213deaff734c.gif);}.good { background: #f23b3e no-repeat; background-image: url(https://img.zcool.cn/community/01adf25bbb4d72a8012099c8c4ba5b.gif);} ...

October 14, 2022 · 1 min · jiezi

关于math:换底公式之推导

\begin{array}{c}换底公式之推导:\\证实:\quad \log_{a}{b}=\frac{\log_{c}{b}}{\log_{c}{a}} \\设:\\\log_{a}{b} =r\\\log_{c}{b} =m\\\log_{c}{a} =n\\即:\\a^r=b\\c^m=b\\c^n=a\\\because a^r=(c^n)^r=b\\\because c^m=b\\\therefore c^m=c^{nr}\\\therefore m=nr\\\because r=\frac{m}{n} \\\therefore \log_{a}{b}=\frac{\log_{c}{b}}{\log_{c}{a}}\\\end{array}

March 25, 2022 · 1 min · jiezi

关于math:十字相乘法推导

\begin{array}{c}十字相乘法之推导:\\设方程\quad (ax+b)(cx+d)=0;\quad (等式左边必须为0)\\则失去:\quad acx^2+(ad+dc)x+bd\\与个别式\quad Ax^2+Bx+C=0\quad 比照:\\A=ac\\B=ad+dc\\C=bd\\即:\\a\quad \quad b\\c\quad \quad d\\重点为4个系数与B的关系:\quad ad+dc=B\\\end{array}

March 25, 2022 · 1 min · jiezi

关于math:二次函数一般式转为顶点式

latex source: \begin{array}{c}一元二次函数式:f(x) = ax^2+bx+c (a≠0)\\令其转化为顶点式形如:f(x) = a(x+h)^2+k (a≠0)的模式\\过程如下:ax^2+bx+c\\a(x^2+\frac{b}{a} x)+c\\a[x^2+\frac{b}{a} x+(\frac{b}{2a})^2]-(\frac{ab^2}{4a^2})+c\\a(x^2+\frac{b}{a}x+\frac{b^2}{4a^2})-\frac{b^2}{4a}+c\\ a(x+\frac{b}{2a} )^2+c-\frac{b^2}{4a}\\ a(x+\frac{b}{2a} )^2+\frac{4ac-b^2}{4a} \\ 因为f(x) = a(x+h)^2+k 的顶点坐标为:(-h,k)\\所以f(x) = ax^2+bx+c 的顶点坐标为:(-\frac{b}{2a},\frac{4ac-b^2}{4a})\\f(x)的图像对于x=-\frac{b}{2a} 对称\end{array}

March 25, 2022 · 1 min · jiezi

关于math:Math类的三个方法比较-floor-ceil-round

public class Test { public static void main(String[] args) { double d1 = 3.4, d2 = 3.6; //负数 double d3 = -3.4, d4 = -3.6; //正数 float f1 = 4.4F, f2 = 4.6F; //负数 float f3 = -4.4F, f4 = -4.6F; //正数 //floor()办法只能接管double类型,返回double类型 //向下取整,返回小于参数的最大整数 System.out.println(Math.floor(d1));//3.0 System.out.println(Math.floor(d2));//3.0 System.out.println(Math.floor(d3));//-4.0 System.out.println(Math.floor(d4));//-4.0 //ceil()办法只能接管double类型,返回double类型 //向上取整,返回大于参数的最小整数 System.out.println(Math.ceil(d1));//4.0 System.out.println(Math.ceil(d2));//4.0 System.out.println(Math.ceil(d3));//-3.0 System.out.println(Math.ceil(d4));//-3.0 //round()办法能够接管double类型,返回long类型 //示意“四舍五入”,算法为Math.floor(x+0.5),行将参数加上0.5后再向下取整 System.out.println(Math.round(d1));//3 System.out.println(Math.round(d2));//4 System.out.println(Math.round(d3));//-3 System.out.println(Math.round(d4));//-4 //round()办法能够接管float类型,返回int类型 System.out.println(Math.round(f1));//4 System.out.println(Math.round(f2));//5 System.out.println(Math.round(f3));//-4 System.out.println(Math.round(f4));//-5 }}

January 5, 2021 · 1 min · jiezi

关于math:Go四舍五入在go语言中为何如此困难

四舍五入是一个十分常见的性能,在风行语言规范库中往往存在 Round 的性能,它起码反对罕用的 Round half up 算法。 而在 Go 语言中这仿佛成为了难题,在 stackoverflow 上搜寻 [go] Round 会存在大量相干发问,Go 1.10 开始才呈现 math.Round 的身影,本认为 Round 的疑难就此结束,然而一看函数正文 Round returns the nearest integer, rounding half away from zero ,这是并不罕用的 Round half away from zero 实现呀,说白了就是咱们了解的 Round 阉割版,精度为 0 的 Round half up 实现,Round half away from zero 的存在是为了提供一种高效的通过二进制办法得后果,能够作为 Round 精度为 0 时的高效实现分支。 带着对 Round 的‘敬畏’,我在 stackoverflow 翻阅大量对于 Round 问题,开启寻求最佳的答案,本文整顿我认为有用的实现,简略剖析它们的优缺点,对于不想逐渐理解,想间接看后果的小伙伴,能够间接看文末的最佳实现,或者跳转 exmath.Round 间接看源码和应用吧! <!--more--> Round 第一弹在 stackoverflow 问题中的最佳答案首先取得我的关注,它在 mathx.Round 被开源,以下是代码实现: ...

January 2, 2021 · 3 min · jiezi

leetcode478-Generate-Random-Point-in-a-Circle

题目要求Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.Note:1. input and output values are in floating-point.2. radius and x-y position of the center of the circle is passed into the class constructor.3. a point on the circumference of the circle is considered to be in the circle.4. randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.Example 1:Input: ["Solution","randPoint","randPoint","randPoint"][[1,0,0],[],[],[]]Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]Example 2:Input: ["Solution","randPoint","randPoint","randPoint"][[10,5,-7.5],[],[],[]]Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]Explanation of Input Syntax:The input is two lists: the subroutines called and their arguments. Solution's constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. randPoint has no arguments. Arguments are always wrapped with a list, even if there aren't any.假设现在已知圆的圆心的x和y坐标,以及该圆的半径radius。要求写一个随机点生成器,要求该生成器生成的点必须在圆内,且每一个点被生成的概率为相等的。规定圆周上的点也属于圆内。 ...

October 9, 2019 · 2 min · jiezi

leetcode453-Minimum-Moves-to-Equal-Array-Elements

题目要求Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.Example:Input:[1,2,3]Output:3Explanation:Only three moves are needed (remember each move increments two elements):[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]从一个长度为n非空整数数组中,找到能够使得数组中每个元素的值都相等的最少步数,一步是指选择对数组中的n-1个元素加一。比如将[1,2,3]这个数组达到均等的最小步数要求为3步,过程如下: [1,2,3][2,3,3][3,3,4][4,4,4]思路和代码假设这个具有n个元素的数组中的最小值为min,这个数组所有元素的和为sum,使其达到均等的最小步数为move,均等的值为target,则可以得到公式sum + (n - 1) * move = target * n。其中,可以推导出target = min + move,即在每一步中都会对初始时最小的元素加一。对二者进行计算可以得出sum - move = min * n。 ...

July 2, 2019 · 1 min · jiezi

leetcode413. Arithmetic Slices

题目要求A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.For example, these are arithmetic sequence:1, 3, 5, 7, 97, 7, 7, 73, -1, -5, -9The following sequence is not arithmetic.1, 1, 2, 5, 7A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.A slice (P, Q) of array A is called arithmetic if the sequence:A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.The function should return the number of arithmetic slices in the array A.Example:A = [1, 2, 3, 4]return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.将包含大于等于三个元素且任意相邻两个元素之间的差相等的数组成为等差数列。现在输入一个随机数组,问该数组中一共可以找出多少组等差数列。 ...

April 23, 2019 · 2 min · jiezi

leetcode423. Reconstruct Original Digits from English

题目要求Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.Note:Input contains only lowercase English letters.Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as “abc” or “zerone” are not permitted.Input length is less than 50,000.Example 1:Input: “owoztneoer"Output: “012"Example 2:Input: “fviefuro"Output: “45"一个非空的英文字符串,其中包含着乱序的阿拉伯数字的英文单词。如012对应的英文表达为zeroonetwo并继续乱序成owoztneoer。要求输入乱序的英文表达式,找出其中包含的所有0-9的数字,并按照从小到大输出。思路和代码首先将数字和英文表示列出来:0 zero1 one2 two3 three4 four5 five6 six7 seven8 eight9 nine粗略一看,我们知道有许多字母只在一个英文数字中出现,比如z只出现在zero中。因此对于这种字母,它一旦出现,就意味着该数字一定出现了。因此一轮过滤后可以得出只出现一次的字母如下:0 zero -> z1 one2 two -> w3 three4 four -> u5 five6 six -> x7 seven8 eight9 nine再对剩下的数字字母过滤出只出现一次的字母:1 one 3 three -> r5 five -> f7 seven -> s8 eight -> g9 nine最后对one和nine分别用o和i进行区分即可。因此可以得出如下代码: public String originalDigits(String s) { int[] letterCount = new int[26]; for(char c : s.toCharArray()) { letterCount[c-‘a’]++; } int[] result = new int[10]; //zero if((result[2] = letterCount[‘z’-‘a’]) != 0) { result[0] = letterCount[‘z’ - ‘a’]; letterCount[‘z’-‘a’] = 0; letterCount[’e’-‘a’] -= result[0]; letterCount[‘r’-‘a’] -= result[0]; letterCount[‘o’-‘a’] -= result[0]; } //two if((result[2] = letterCount[‘w’-‘a’]) != 0) { letterCount[’t’-‘a’] -= result[2]; letterCount[‘w’-‘a’] = 0; letterCount[‘o’-‘a’] -= result[2]; } //four if((result[4] = letterCount[‘u’-‘a’]) != 0) { letterCount[‘f’-‘a’] -= result[4]; letterCount[‘o’-‘a’] -= result[4]; letterCount[‘u’-‘a’] -= result[4]; letterCount[‘r’-‘a’] -= result[4]; } //five if((result[5] = letterCount[‘f’-‘a’]) != 0) { letterCount[‘f’-‘a’] -= result[5]; letterCount[‘i’-‘a’] -= result[5]; letterCount[‘v’-‘a’] -= result[5]; letterCount[’e’-‘a’] -= result[5]; } //six if((result[6] = letterCount[‘x’-‘a’]) != 0) { letterCount[’s’-‘a’] -= result[6]; letterCount[‘i’-‘a’] -= result[6]; letterCount[‘x’-‘a’] -= result[6]; } //seven if((result[7] = letterCount[’s’-‘a’]) != 0) { letterCount[’s’-‘a’] -= result[7]; letterCount[’e’-‘a’] -= result[7] * 2; letterCount[‘v’-‘a’] -= result[7]; letterCount[’n’-‘a’] -= result[7]; } //one if((result[1] = letterCount[‘o’-‘a’]) != 0) { letterCount[‘o’-‘a’] -= result[1]; letterCount[’n’-‘a’] -= result[1]; letterCount[’e’-‘a’] -= result[1]; } //eight if((result[8] = letterCount[‘g’-‘a’]) != 0) { letterCount[’e’-‘a’] -= result[8]; letterCount[‘i’-‘a’] -= result[8]; letterCount[‘g’-‘a’] -= result[8]; letterCount[‘h’-‘a’] -= result[8]; letterCount[’t’-‘a’] -= result[8]; } //nine if((result[9] = letterCount[‘i’-‘a’]) != 0) { letterCount[’n’-‘a’] -= result[9] * 2; letterCount[‘i’-‘a’] -= result[9]; letterCount[’e’-‘a’] -= result[9]; } result[3] = letterCount[’t’-‘a’]; StringBuilder sb = new StringBuilder(); for(int i = 0 ; i<result.length ; i++) { for(int j = 0 ; j<result[i] ; j++) { sb.append(i); } } return sb.toString(); }上面的代码未免写的太繁琐了,对其进一步优化可以得到如下代码: public String originalDigits2(String s) { int[] alphabets = new int[26]; for (char ch : s.toCharArray()) { alphabets[ch - ‘a’] += 1; } int[] digits = new int[10]; digits[0] = alphabets[‘z’ - ‘a’]; digits[2] = alphabets[‘w’ - ‘a’]; digits[6] = alphabets[‘x’ - ‘a’]; digits[8] = alphabets[‘g’ - ‘a’]; digits[7] = alphabets[’s’ - ‘a’] - digits[6]; digits[5] = alphabets[‘v’ - ‘a’] - digits[7]; digits[3] = alphabets[‘h’ - ‘a’] - digits[8]; digits[4] = alphabets[‘f’ - ‘a’] - digits[5]; digits[9] = alphabets[‘i’ - ‘a’] - digits[6] - digits[8] - digits[5]; digits[1] = alphabets[‘o’ - ‘a’] - digits[0] - digits[2] - digits[4]; StringBuilder sb = new StringBuilder(); for (int d = 0; d < 10; d++) { for (int count = 0; count < digits[d]; count++) sb.append(d); } return sb.toString(); } ...

April 20, 2019 · 3 min · jiezi

JavaScript 精粹:Number 与 Math

这是 JavaScript 精粹的系列篇,涵盖了 JavaScript 中最常用和最重要的方法,以及其它一些基础知识。在这篇文章中,我们将讨论 Number 和 Math前置知识建议大家了解类型,只需要一点数学知识。JavaScript Essentials: Types & Data StructuresJavaScript 中的数字基础JavaScript 只有一种数字类型,如 5 和 5.12 是相同的类型。JS 使用“双精度64位格式IEEE 754”标准这是什么意思? 所有JavaScript 数字都存储为双浮点数。 JS会欺骗你,让你认为 var x = 1 是一个整数,但实际上它是一个浮点数并且等于 1.0。如果你这方面感兴趣,以下一些链接供你参考:ECMAScript® 2018 Language SpecificationHere is what you need to know about JavaScript’s Number type本文的重点是 Number 对象的方法。https://medium.com/dailyjs/ja…数字创建和基本的代码重要指南所有数字都是浮点数所有的数字都是相同的类型,’number’JS与任何其他语言一样,受限于它可以表示的数字大小以及它的准确程度。常用的方法“安全” 的数字一个 “安全” 的数字是一个值保证为你所说的值的数字。例如,如果试图在代码中使用900719925474099164,它就会变成 900719925474099200,这是因为它超出了安全数字范围。我们怎么知道安全数字的范围是多少?如何确定一个数字是否是整数?如何更改小数位数?转换成指数形式也被称为科学记数法。全局 Number 方法 与 Number.method 比较你可能已经注意到有像 parseInt 这样的全局函数,但是这里只用 Number.parseInt()这是因为 JS 试图摆脱全局函数而使用模块。一些新的模块方法被更新,而旧的全局方法没有更新。 比如 isNan() 不同于 Number.isNan()。使用大数字警告:下面提到的 vanilla JS 方法目前在这个的时间段内不可用。 (可以在 Chrome控制台中尝试)在此处 查看提案。在BigInt 可用之前,请使用库 MikeMcl/bignumber.js 。转换为另一个数字系统数字使用字符串中的方法你可能已经尝试在控制台或任何地方上数字使用字符串的方法如 23.toString(2) // syntax error这是因为如前面“数字创建基础”中提到的 23.,0 是可选的。这意味着当你做 23.tostring(2), JS 认为它只是一个数字。它应该足够聪明,知道正在调用一个方法,但是好吧。解决方案:将数字包在括号中 (23).toString(2) //“10111” 或做一些非常奇怪的事…… 23..toString(2) 但请不要这样做 ????NaN 是 Number 类型NaN 存在于 Number 对象上,但是被定义为某些数学运算的结果,这些运算导致无法将数值量化为数字。 或者换句话说,它的命名很差, “无效数字”或类似数字情况会更好。检查 NaNNaN 是有毒的,意思是它会把它接触到的任何东西变成 请输入代码NaN 。它是唯一不等于它本身的值,我们可以利用它来做一些像 x !== x 的事情,如果它返回 true,那么它就是 NaN。四舍五入一个数字的方法指数生成随机数Math 方法在这里只包含了一些 Math 方法,但是有很多方法,请查看文档。我没有把它们全部包括在内,因为它们不言自明,并且只在你处理一个数字很多且重要的项目时才会经常使用。Math实践Convert a Number to a String!Square Every DigitIs this a triangle?Playing with digitsMultiples of 3 or 5原文:https://codeburst.io/javascri…你的点赞是我持续分享好东西的动力,欢迎点赞!一个笨笨的码农,我的世界只能终身学习!更多内容请关注公众号《大迁世界》! ...

February 26, 2019 · 1 min · jiezi

leetcode390.Elimination Game

题目要求There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.We keep repeating the steps again, alternating left to right and right to left, until a single number remains.Find the last number that remains starting with a list of length n.Example:Input:n = 9,1 2 3 4 5 6 7 8 92 4 6 82 66Output:6假设有1-n一共n个数字,从左往右开始每隔一位删除一个数字,到达最右侧后,再从右往左每隔一位删除一个数字,如此反复,直到剩下最后一个数字。问最后剩下的数字是多少。思路一:递归先从一个例子入手,当n等于7时,数字序列为1,2,3,4,5,6,7, 删除序列如下:1 2 3 4 5 6 7 2 4 6 4可以看到,第一轮删除后剩下的2,4,6就相当于是1,2,3的两倍,我们可以等价于从右往左删除1,2,3后剩余的结果乘2。由此可见,假如我们定义一个递归函数f(n, left),我们可以有f(n/2, right)来获取结果。 public int lastRemaining(int n) { return lastRemaining(n, true); } public int lastRemaining(int n, boolean left) { if(n == 1) { return 1; } if(n % 2 == 1) { return lastRemaining(n / 2, !left) * 2; }else{ if( left ) { return lastRemaining(n/2, !left) * 2; }else { return lastRemaining(n/2, !left) * 2 -1; } } }思路二这里其实存在一个镜像删除的问题,也就是说,对于任何一个1~n的序列来说,从左往右开始删除和从右往左开始删除剩余的结果的和一定为(n+1),也就是所谓的镜像删除问题。举个例子:从左往右开始删除1 2 3 4 5 6 2 4 6 4 从右往左开始删除1 2 3 4 5 61 3 5 3 可以看到二者剩余的值加起来一定为n+1即7。根据这个原理,我们可以优化上面的递归,无需再利用left值来标记是从左往右删除还是从右往左删除,直接执行镜像删除即可。 public int lastRemaining2(int n) { return n == 1 ? 1 : (1 + n / 2 - lastRemaining2(n/2)) * 2; } ...

February 12, 2019 · 1 min · jiezi

[LeetCode] 223. Rectangle Area

ProblemFind the total area covered by two rectilinear rectangles in a 2D plane.Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.Example:Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2Output: 45Note:Assume that the total area is never beyond the maximum possible value of int.Solutionclass Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int a1 = (C-A)(D-B); int a2 = (G-E)(H-F); int left = Math.max(A,E); int right = Math.min(C,G); int top = Math.min(D,H); int bottom = Math.max(B,F); if (left < right && bottom < top) return a1+a2-(right-left)*(top-bottom); else return a1+a2; }} ...

January 14, 2019 · 1 min · jiezi

[LeetCode] 402. Remove K Digits

ProblemGiven a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.Note:The length of num is less than 10002 and will be ≥ k.The given num does not contain any leading zero.Example 1:Input: num = “1432219”, k = 3Output: “1219"Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.Example 2:Input: num = “10200”, k = 1Output: “200"Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.Example 3:Input: num = “10”, k = 2Output: “0"Explanation: Remove all the digits from the number and it is left with nothing which is 0.Solutionclass Solution { public String removeKdigits(String num, int k) { Deque<Character> stack = new ArrayDeque<>(); int n = num.length(); if (k >= n) return “0”; for (int i = 0; i < n; i++) { while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) { stack.pop(); k–; } stack.push(num.charAt(i)); } while (k > 0) { stack.pop(); k–; } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) sb.append(stack.pop()); sb.reverse(); while (sb.length() > 1 && sb.charAt(0) == ‘0’) sb.deleteCharAt(0); return sb.toString(); }} ...

December 26, 2018 · 1 min · jiezi

[LeetCode] 258. Add Digits

ProblemGiven a non-negative integer num, repeatedly add all its digits until the result has only one digit.Example:Input: 38Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.Follow up:Could you do it without any loop/recursion in O(1) runtime?Solution 1class Solution { public int addDigits(int num) { int sum = 0, cur = num; if (num < 10) return num; while (num >= 10) { while (num >= 10) { sum += num%10; num /= 10; } sum += num; if (sum >= 10) { num = sum; sum = 0; } else return sum; } return sum; }}Solution 2 - Mod 9public class Solution { public int addDigits(int num) { if (num == 0){ return 0; } if (num % 9 == 0){ return 9; } else { return num % 9; } }} ...

December 26, 2018 · 1 min · jiezi

较常用的Math方法及ES6中的扩展

记录下与Math有关的常用方法,如:求最大值、最小值等,或者是保留几位数啥的1.数据let floatA = 2.325232;let floatB = 2.3456;let temporaryArray = [1, 2, 5, 6, 3];let minusNum = -12;let minusFloat = -12.321;let intA = 10;let min, max, num;2.求最大值、最小值{ /* 求最小值 / min = Math.min(floatA, floatB); console.log(min); / 使用apply来重新绑定this / min = Math.min.apply(null, temporaryArray); console.log(min); / 使用展开运算符 / min = Math.min(…temporaryArray); console.log(min); / 求最大值 / max = Math.max(floatA, floatB); console.log(max); / 使用apply来重新绑定this / max = Math.max.apply(null, temporaryArray); console.log(max); / 使用展开运算符 / max = Math.max(…temporaryArray); console.log(max);}3.取整{ / 四舍五入取整:取与参数最接近的整数 / num = Math.round(floatA); console.log(num); num = Math.round(minusFloat); console.log(num); / 向上取整:取大于或等于函数参数,并且与之最接近的整数 / num = Math.ceil(floatB); console.log(num); / 向下取整:取小于或等于函数参数,并且与之最接近的整数 / num = Math.floor(floatB); console.log(num); / ceil、floor结合起来,实现一个总是返回数值的整数部分的函数 / function getInteger(value) { value = Number(value); return value < 0 ? Math.ceil(value) : Math.floor(value); } console.log(getInteger(-2.3322));}4.求绝对值{ / 负整数 / num = Math.abs(minusNum); console.log(num); / 负浮点数 / num = Math.abs(minusFloat); console.log(num);}5.次幂{ / 结果是虚数或负数,则该方法将返回 NaN * 如果由于指数过大而引起浮点溢出,则该方法将返回 Infinity / / 2的3次方 / num = Math.pow(2, 3); console.log(num);}6.去平方根{ / 求参数的平方根,如果参数小于 0,则返回 NaN / num = Math.sqrt(9); console.log(num);}7.生成随机数{ / 生成0-1的随机数,大于0小于1 / num = Math.random(); console.log(num); / 生成0-10的随机数 / num = Math.random() * 10; console.log(num); / 生成任意范围随机数 / function getRandom(min, max) { return Math.random() * (max - min) + min; } console.log(getRandom(3.5, 6.5)); / 整数min与整数max生成任意范围整数随机数 / function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandomInt(5, 15));}8.es6中对Math方法的扩展(部分){ / 取整(非四舍五入) * 对于非数值,内部调用 Number 强转为数值 * 对于空值或其他数据,返回NaN * / num = Math.trunc(floatA); console.log(num); num = Math.trunc(intA); console.log(num); num = Math.trunc(‘aaa’); console.log(num);}{ / 判断一个数是正数、负数或零 * 正数返回+1,负数返回-1,零返回0或-0 * 其他值 NaN * / num = Math.sign(2); console.log(num); num = Math.sign(0); console.log(num); num = Math.sign(-0); console.log(num); num = Math.sign(-14); console.log(num); num = Math.sign(‘ss’); console.log(num);}{ let a = 2; a *= 3; / 相当于 aa*a / console.log(a);}9.保留位数操作{ / 四舍五入保留两位小数 * toFixed(num) 方法可把 Number型 四舍五入为指定小数位数的数字 * num规定小数的位数,是 0 ~ 20 之间的值,包括 0 和 20 * 有些实现可以支持更大的数值范围,如果省略了该参数,将用 0 代替 * / num = floatA.toFixed(2); console.log(num); let word = 2.5; num = word.toFixed(); console.log(num); / 不四舍五入 / num = Math.floor(23.365125 * 100) / 100; console.log(num);}10.字符串转数字 { / parseInt(value, radix) * 用于解析字符串,返回一个整数 * radix表示要解析的数字的基数,该值介于 2 ~ 36 之间 * 如果省略该参数或其值为 0,则数字将以 10 为基础来解析 * 如果它以 “0x” 或 “0X” 开头,将以 16 为基数 * 如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN。 * / let temporaryString = ‘123’; num = parseInt(temporaryString); console.log(num); { console.log(parseInt(“10”)); //返回 10 console.log(parseInt(“19”,10)); //返回 19 : 10 + 9 console.log(parseInt(“11”,2)); //返回 3 : 2 + 1 console.log(parseInt(“17”,8)); //返回 15 : 8 + 7 console.log(parseInt(“1f”,16)); //返回 31 : 16 + 15 console.log(parseInt(“010”)); //未定:返回 10 或 8 } / 常见的parseInt一道题 / { console.log([‘1’, ‘2’, ‘3’].map(parseInt)); / 返回[1, NaN, NaN] * map(function(value, index, array) {}) * map方法中的回调函数中的3个参数值,每个值value,索引值index,数组对象array * 上面的相当于parseInt(‘1’, 0)、parseInt(‘2’, 1)、parseInt(‘3’, 2) * / } / Number强转 */ num = Number(‘12345’); console.log(num);}正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)往期好文推荐:判断iOS和Android及PC端纯css实现瀑布流(multi-column多列及flex布局)微信小程序之购物车和父子组件传值及calc的注意事项css实现波浪线及立方体 ...

November 28, 2018 · 3 min · jiezi

leetcode397. Integer Replacement

题目要求Given a positive integer n and you can do operations as follow:If n is even, replace n with n/2.If n is odd, you can replace n with either n + 1 or n - 1.What is the minimum number of replacements needed for n to become 1?Example 1:Input:8Output:3Explanation:8 -> 4 -> 2 -> 1Example 2:Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1思路和代码可以发现除二后所得到的结果一定优于加减1。因此,如果当前奇数除二为偶数,则直接做除法,否则将当前奇数加一再除以二,得到偶数的结果。 public int integerReplacement(int n) { int count = 0; while(n != 1){ if((n & 1) == 0){ n >>>= 1; } else if(n == 3 || ((n>>>1) & 1) == 0){ n–; } else{ n++; } count++; } return count; } ...

November 26, 2018 · 1 min · jiezi

leetcode396. Rotate Function

题目要求Given an array of integers A and let n to be its length.Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a “rotation function” F on A as follow:F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1].Calculate the maximum value of F(0), F(1), …, F(n-1).Note:n is guaranteed to be less than 105.Example:A = [4, 3, 2, 6]F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.Bk代表对数组A在位置k上进行顺时针的旋转后生成的数组。F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1],要求返回获得的最大的F(k)的值。暴力循环按照题目的要求,执行两次循环即可以获得F(k)的所有值,只需要从中比较最大值即可。 public int maxRotateFunction(int[] A) { if(A == null || A.length == 0) return 0; int max = Integer.MIN_VALUE; for(int i = 0 ; i < A.length ; i++) { int value = 0; for(int j = 0 ; i < A.length ; j++) { value += j * A[(j+i)%A.length]; } max = Math.max(value, max); } return max; }数学思路F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1]F(k-1) = 0 * Bk-1[0] + 1 * Bk-1[1] + … + (n-1) * Bk-1[n-1] F(k) = F(k-1) + sum - n*Bk[0]k = 0 Bk[0] = A[0]k = 1 Bk[0] = A[len-1]k = 2 Bk[0] = A[len-2]… public int maxRotateFunction(int[] A) { if(A == null || A.length == 0) return 0; int F = 0; int sum = 0; for(int i = 0 ; i<A.length ; i++) { sum += A[i]; F += i * A[i]; } int max = F; for(int i = 1 ; i<A.length ; i++) { F += sum - A.length * A[A.length - i]; max = Math.max(F, max); } return max; } ...

November 26, 2018 · 2 min · jiezi