add: 最大数值

This commit is contained in:
yi-ge 2020-05-05 20:25:19 +08:00
parent 55a05f31c9
commit 64843298d3
3 changed files with 43 additions and 0 deletions

View File

@ -269,6 +269,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 46. 全排列 https://leetcode-cn.com/problems/permutations/ - LeetCode 46. 全排列 https://leetcode-cn.com/problems/permutations/
- LintCode 15. 全排列 https://www.lintcode.com/problem/permutations/description - LintCode 15. 全排列 https://www.lintcode.com/problem/permutations/description
- [最大数值](src/math/maximum-lcci.js)
- LeetCode 面试题 16.07. 最大数值 https://leetcode-cn.com/problems/maximum-lcci/
## 堆 ## 堆
- [超级丑数](src/stack/super-ugly-number.js)【未完成】 - [超级丑数](src/stack/super-ugly-number.js)【未完成】

31
src/math/maximum-lcci.js Normal file
View File

@ -0,0 +1,31 @@
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
export const maximum = function (a, b) {
// return Math.max(a, b)
// 不得使用if-else或其他比较运算符那么我们也尽可能回避abs、max这些函数
// return (a + b) / 2 + Math.abs(a - b) / 2
// return (a + b) / 2 + Math.abs(a - (a + b) / 2)
// return ((a + b) + Math.abs(a - b)) / 2
// 1.两个符号相同不会溢出,符号不同可能溢出
// 2.所以的分别对ab两值的符号位求异或
// 3.符号相同直接取k符号不同,判断a的符号位
const ak = a >>> 63
const bk = b >>> 63 // 符号位
const diff = ak ^ bk// 求异或相同为0不同为1
let k = (a - b) >>> 63
// 如果符号相同就取k符号不同就判断ak符号得出k,是0还是1
k = k & (diff ^ 1) | (ak & diff)
return b * k + a * (k ^ 1)
// const k = ((a - b) >> 63) & 1
// return b * k + a * (k ^ 1)
// const k = (a - b) >>> 63
// return b * k + a * (k ^ 1)
// k就是把符号位取出来1是负数0是正数。负数说明b大所以b*1+a*0不就是b吗。反之如果是正数说明a大那么就是b*0+a*1就等于 a了。
}

View File

@ -0,0 +1,8 @@
import { maximum } from '../../src/math/maximum-lcci'
test('最大数值', () => {
expect(maximum(1, 2)).toBe(2)
expect(maximum(108, 133)).toBe(133)
expect(maximum(199, 133)).toBe(199)
expect(maximum(2147483647, -2147483648)).toBe(2147483647)
})