携程开发笔试8.30
4道编程 总分100
没时间写思路了,仅纪念+求第三题思路
第一题(100%)
let q = parseInt(readline()); // 表示有q次询问 while (q--) { let num = parseInt(readline()); // 得到数字 if (num % 2 === 0) { console.log(num); } else { console.log(fn(num)); } } function fn(num) { let numArr = [...num.toString()]; // 找到有没有偶数的存在 let flag = numArr.some(item => parseInt(item) % 2 === 0); // 找有没有0 let zerosFlag = numArr.some(item => item === '0'); let res; if (!flag) { return -1; } else { if (zerosFlag) { let index = numArr.indexOf('0'); numArr.splice(index, 1) res = [...numArr, '0'] } else { let even = numArr.filter(item => parseInt(item) % 2 ===0)[0]; let index = numArr.indexOf(even); numArr.splice(index, 1); res = [...numArr, even]; } return parseInt(res.join('')); } }
第二题(100%)
let q = parseInt(readline()); while (q--) { let [a, b, c] = readline().split(' ').map(item => parseInt(item)); let count1 = Math.min(a, b, c); let count2 = b - count1; let res = count1 * 2; res = count2 === 0 ? res : res + count2 - 1; console.log(res); }
第三题(6.25%)
第三题写了一个小时啥也没写出来,不知道是不是题目没看清想复杂了...不想说了
第四题(100%)
const n = 5, nums = [-1, 1, 2, 5, 7]; function fn4(n, nums) { if (n <= 2) return 0; let [value, index] = helper(n, nums); let dp = []; for (let i = index - 1; i <= index + 1; i++) { if (i === 0) { let temp = [...nums]; temp[0] = temp[1]; dp.push(helper(n, temp)[0]) } else if (i === n-1) { let temp = [...nums]; temp[n-1] = temp[n-2]; dp.push(helper(n, temp)[0]) } else { let temp = [...nums]; temp[i] = Math.floor((nums[i-1] + nums[i+1])/2); dp.push(helper(n, temp)[0]); } } return Math.min(...dp); } // 统计平滑值最大的函数 function helper(n, nums) { let value = -1, index = -1; for (let i = 1; i < n; i++) { let temp = Math.abs(nums[i-1]-nums[i]); if (temp > value) { value = temp; index = i; } } return [value, index]; } console.log(fn4(n, nums));#携程笔试#