题解 | #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())
全部评论

相关推荐

06-20 21:22
已编辑
门头沟学院 Java
纯真的河老师在喝茶:答应了就跑啊,实习随便跑啊,别被pua了,md就是找个廉价劳动力,还平稳过度正式工,到时候跟你说没转正
点赞 评论 收藏
分享
迟缓的斜杠青年巴比Q...:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务