Separate an integer into two (nearly) equal parts
我需要把一个整数分成两个数字。类似于除以2,但我只希望得到整数组件,例如:
1 2 | 6 = 3 and 3 7 = 4 and 3 |
我尝试了以下方法,但我不确定它是否是最佳解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 | var number = 7; var part1 = 0; var part2 = 0; if((number % 2) == 0) { part1 = number / 2; part2 = number / 2; } else { part1 = parseInt((number / 2) + 1); part2 = parseInt(number / 2); } |
这是我想要的,但我不认为这个代码是干净的。
有更好的方法吗?
只需找到第一部分,然后从原始数字中减去它。
1 2 3 4 5 6 | var x = 7; var p1 = Math.floor(x / 2); var p2 = x - p1; console.log(p1, p2); |
如果
让javascript为您计算。
1 2 3 4 | var x = 7; var p1 = Math.ceil(x / 2); var p2 = Math.floor(x / 2); console.log(p1, p2); |
您的代码可以简化一点:
1 2 3 4 5 6 7 8 | var num = 7; var p1 = Math.floor(num / 2); var p2 = p1; if (num % 2 != 0) { p1++; } console.log(p1, p2); |
1 2 3 4 5 6 | var num = 7; var part1 = parseInt(num/2); var part2 = num - part1; console.log(part1, part2); |
另一种方法是使用位运算符。它不适用于非常大的数字
1 2 3 4 5 6 7 8 9 10 | function splitter(number){ part1 = (number>>1) + (number&1); part2 = number>>1; console.log(number +":", part1 +"+" + part2); } splitter(7); splitter(6); splitter(2**30+1); // Breaks for values greater than 2**31 splitter(2**31+1); |
1 2 3 4 5 | var x = 11; var a = Math.ceil(x/2); var b = x-a; console.log("x =" + x +" , a =" + a +" , b =" + b); |
如果您不希望输出是连续的或完全相同的,但又想"将一个整数分成两个数字",那么这是您的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 | function printSeparatedInts(num) { let smallerNum = Math.floor(Math.random() * Math.floor(num)); if (num && smallerNum === (num/2)) { // checking if input != 0 & output is not consecutive printSeparatedInts(num) } else { console.log(smallerNum, (num - smallerNum)) } } printSeparatedInts(22) printSeparatedInts(22) // will likely print different output from above printSeparatedInts(7) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | var number = 7; var part1 = 0; var part2 = 0; if(number == 0) { part1 = (part2 = 0); console.log(part1, part2); } else if(number == 1) { part1 = 1; part2 = 0; console.log(part1, part2); } else if((number % 2) == 0) { part1 = part2 = number / 2; console.log(part1, part2); } else { part1 = (number + 1) / 2; part2 = number - part1; console.log(part1, part2); } |
只有其他的办法,我觉得性能还可以。
感觉懒惰吗?没问题!
我自豪地向您展示一个发电机对象!
初始化并使用它!即使在同一行中,它也会自动更改其他每次使用的值!!
用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function splitter(n){ this.p1 = Math.floor(n/2); this.p2 = n-this.p1; this.cnt=0; this.valueOf= ()=> (++this.cnt%2)? this.p1:this.p2; return n; } a = new splitter(5); console.log(a +" and" +a); console.log(a +" and" +a); console.log(a +" and" +a); b = new splitter(11); console.log(b +" and" +b); |
或者这样:
1 2 3 4 5 | var number = 7; var part1 = ~~((number / 2) + (number % 2)); var part2 = ~~(number / 2); console.log(part1, part2); |
1 2 3 4 5 | var n = 7; var p1 = (n - (n % 2)) / 2; var p2 = (n + (n % 2)) / 2; console.log(p1, p2); |