题解 | #24点运算#
24点运算
http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
const d = { 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, J: 11, Q: 12, K: 13, A: 1, 2: 2 }
const res = []
function f(nums, target) {
if (nums.length == 1) {
if (d[nums[0]] == target) {
res.push(nums[0])
return true
} else {
return false
}
}
for (let i = 0; i < nums.length; i++) {
const a = nums[i]
const b = nums.slice(0, i).concat(nums.slice(i + 1))
if (f(b, target + d[a])) {
res.push('-' + a)
return true
} else if (f(b, target - d[a])) {
res.push('+' + a)
return true
} else if (f(b, target * d[a])) {
res.push('/' + a)
return true
} else if (target % d[a] === 0 && f(b, target / d[a])) {
res.push('*' + a)
return true
}
}
return false
}
function get24(str) {
var nums = str.split(' ')
if (nums.includes('joker') || nums.includes('JOKER')) {
console.log('ERROR')
} else {
if (f(nums, 24)) {
console.log(res.join(''))
} else {
console.log('NONE')
}
}
}
get24(readline())