在线地址:https://www.nowcoder.com/exam/oj/ta?page=1&tpId=37&type=37
我用的是 JavaScript Node
HJ1 字符串最后一个单词的长度
console.log(line.split(' ').pop().length)
HJ2 计算某字符出现次数
const str = line.toLowerCase();
const word = (await readline()).toLowerCase();
console.log([...str].reduce((total,cur)=>{
if(cur == word){
total ++;
}
return total;
},0));
注意用await readline()
读取第二个参数
HJ3 明明的随机数
这题数据收集的方式比较特别
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let list = [];
rl.on('line', function (line) {
list.push(+line);
if(list.length -1 === list[0]){
list.shift();
list = Array.from(new Set(list));
list.sort((a,b)=>a-b);
list.forEach(item=>{
console.log(item);
})
}
});
HJ4 字符串分隔
我一开始想到用正则表达式,就要针对字符串是不是 8 的整倍数做处理。
const wordLength = 8;
const regExp = new RegExp(`\\w{${wordLength}}`, "g");
let wordList = [];
let resultList;
while ((resultList = regExp.exec(line)) != null) {
wordList.push(resultList[0]);
}
let str = "";
if (!wordList.length) {
str = line;
} else {
str = line.slice(wordList.length * wordLength);
}
if (str) {
wordList.push(str);
}
wordList = wordList.map(item=>item.padEnd(8,"0"));
wordList.forEach((item) => {
console.log(item);
});
看了下题解,递归加slice
更简单,这种题确实应该首先想到递归。而且考算法和平时写代码还是不一样的,更专注结果的输出。
const wordLength = 8;
inner(line);
function inner(data) {
if (data.length > 8) {
console.log(data.slice(0, wordLength));
inner(data.slice(wordLength));
} else {
console.log(data.padEnd(wordLength, "0"));
}
}
HJ5 进制转换
使用 +
、parseInt
、number
都是可以的,但直接考进制转换,这么实现还是不太好,或许没有明令禁止就可以?我有点虚。
const infos = Array(6)
.fill(1)
.map((item, index) => String.fromCharCode(65 + index))
.reduce((pre, cur) => {
let value = cur.charCodeAt() - 55;
pre[cur] = value;
return pre;
}, {});
const num = line
.substr(2)
.split("")
.reverse()
.reduce(
(pre, cur, index) => pre + (infos[cur] || cur) * Math.pow(16, index),
0
);
console.log(num);
其实infos
就是{ A:10,B:11,C:12,D:13,E:14,F:15,}
,还是直接写的好,这里多巩固了String.fromCharCode
和charCodeAt
两个 api
以0xAA
举例,对应的 10 进制转换过程是 10*1 + 10*16
=> 170,问 171 的 16 进制是多少
质数因子
受到前面的影响我想到了递归
let list = [],
max = Math.sqrt(line);
function inner(num) {
let flag = false;
let i = 2;
for (; i <= max; i++) {
if (num % i == 0) {
list.push(i);
flag = true;
break;
}
}
if (flag) {
inner(num / i);
} else if (num != 1) {
list.push(num);
}
}
inner(line);
console.log(list.join(" "));
可这道题用循环的方式更简单,因为会有重复的因子,关于line != 1
我是都没有想到的
function able(line) {
let list = [],
max = Math.sqrt(line);
for (let i = 2; i <= max; i++) {
while (line % i == 0) {
list.push(i);
line /= i;
}
}
if (line != 1) {
list.push(line);
}
console.log(list.join(" "));
}
HJ7 取近似值
let [a,b] = line.split(".");
a = +a;
if("0."+b >= 0.5){
console.log(a+1);
}
else{
console.log(a);
}
HJ8 合并表记录
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let count = 0,max = 0,infos = {};
rl.on('line', function (line) {
if(max == 0){
max = line
}
else{
const [key,value] = line.split(" ");
if(!infos[key]){
infos[key] = 0;
}
infos[key] += +value;
count++;
if(count == max){
Object.keys(infos).forEach(key=>{
console.log(`${key} ${infos[key]}`)
})
}
}
});
HJ9 提取不重复的整数
console.log([...new Set(line.split('').reverse())].join(""));
HJ10 字符个数统计
console.log([...new Set(line.split(""))].length);
HJ11 数字颠倒
console.log(line.split("").reverse().join(""))
HJ12 字符串反转
console.log(line.split("").reverse().join(""))
HJ13 句子逆序
console.log(line.split(" ").reverse().join(" "));
HJ14 字符串排序
function able(list) {
for (let i = 0; i < list.length - 1; i++) {
let current = list[i],
swapIndex = -1;
for (let j = i + 1; j < list.length; j++) {
let next = list[j],
flag = false;
for (let f = 0; f < Math.max(current.length, next.length); f++) {
if (!next[f] || !current[f]) {
if (next.length < current.length) {
flag = true;
break;
}
} else if (next[f] < current[f]) {
flag = true;
break;
} else if (next[f] > current[f]) {
break;
}
}
if (flag) {
current = next;
swapIndex = j;
}
}
if (swapIndex != -1) {
[list[i], list[swapIndex]] = [list[swapIndex], list[i]];
}
}
console.log(list.join("\n"));
}
able(["boat", "boot", "to", "cap", "cat", "two", "too", "up", "card"]);
前面漏了else if (next[f] > current[f])
和 Math.max(current.length, next.length);
造成了一些奇怪现象
HJ15 求 int 型正整数在内存中存储时 1 的个数
function able(line) {
console.log(
parseInt(line)
.toString(2)
.split("")
.reduce((total, cur) => {
if (cur == 1) {
total++;
}
return total;
}, 0)
);
}
实则利用match
的特性会更简单
console.log(num.match(/1/g).length);
10 进制转换为二进制,就是一直用 2 求余,第一个出现的余数是右面第一个
function able(num) {
let result = "";
if (num == 0) {
return 0;
}
while (num > 0) {
result = (num % 2) + result;
num = (num / 2) | 0;
}
return result;
}