问:
- 剑指 Offer 14- II. 剪绳子 II
- 剑指 Offer 15. 二进制中1的个数
- 剑指 Offer 16. 数值的整数次方
- 剑指 Offer 17. 打印从1到最大的n位数
- 剑指 Offer 18. 删除链表的节点
解: 1.
const cuttingRope = function(n) {
if (n < 4) return n - 1
const mod = 1000000007
let res = 1
while (n > 4) {
res = (res * 3) % mod
n -= 3
}
return res * n % mod
};
const hammingWeight = function(n) {
let num = 0
while ((n & (~n + 1)) !== 0) {
num++
n ^= (n & (~n + 1))
}
return num
};
const myPow = function(x, n) {
function getRes(a, b) {
if (b === 0) return 1
if (b === 1) return a
if (b === -1) return 1 / a
if (b % 2 === 0) {
const res = getRes(a, b / 2)
return res * res
} else {
const res = getRes(a, (b - 1) / 2)
return res*res*x
}
}
return getRes(x, n)
};
const printNumbers = function(n) {
const target = (''+9).repeat(n)
const res = []
for (let i = 1; i <= +target; i++) {
res.push(i)
}
return res
};
const deleteNode = function(head, val) {
let curNode = head
let pre = null
while (curNode) {
if (curNode.val === val) {
if (curNode.val === head.val) {
return curNode.next
} else {
pre.next = curNode.next
return head
}
} else {
pre = curNode
curNode = curNode.next
}
}
};