前端刷华为机考17-18题

2023-09-06  本文已影响0人  小遁哥

HJ17 坐标移动

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // Write your code here
    while(line = await readline()){
        let x = 0,y = 0;
        line.split(";").filter(Boolean).forEach(pos=>{
            [...pos.matchAll(/^([A-Z])(\d+)$/g)].forEach(list=>{
                if(list[1] == 'A'){
                    x -= +list[2]
                }
                else if(list[1] == 'D'){
                    x += +list[2]
                }
                else if(list[1] == 'W'){
                    y += +list[2]
                }
                else{
                    y -= +list[2]

                }
            });
        })

        console.log(x+','+y)
    }
}()

HJ18 识别有效的 IP 地址和掩码并进行分类统计

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
let infos = {
    a: 0,
    b: 0,
    c: 0,
    d: 0,
    e: 0,
    error: 0,

    private: 0,
};
rl.on("line", function (line) {
    const [ipList, codeList] = line
        .split("~")
        .map((item) => item.split(".").filter(Boolean).map(item=>+item));


    let isError = false;

    if (ipList[0] == 0 || ipList[0] == 127) {
        return;
    }

    if (ipList.length != 4 || ipList.some((item) => item > 255 || item < 0)) {
        infos.error++;
        isError = true;
    } else if (
        codeList.length != 4 ||
        codeList.reduce((pre,cur)=>pre + cur.toString(2).padStart(8,'0'),"").match(/^1+0+$/) == null
    ) {
        infos.error++ ;
        isError = true;
    }




    if (!isError) {

            if (ipList[0] >= 1 && ipList[0] <= 126) {

                infos.a++;
            }
            if (ipList[0] >= 128 && ipList[0] <= 191) {
                infos.b++;
            }
            if (ipList[0] >= 192 && ipList[0] <= 223) {
                infos.c++;
            }
            if (ipList[0] >= 224 && ipList[0] <= 239) {
                infos.d++;
            }
            if (ipList[0] >= 240 && ipList[0] <= 255) {
                infos.e++;
            }


        if (
            ipList[0] == 10 ||
            (ipList[0] == 172 && ipList[1] >= 16 && ipList[1] <= 31) ||
            (ipList[0] == 192 && ipList[1] == 168)
        ) {
            infos.private++;
        }
    }
});
rl.on("close", () => {
    console.log(
        Object.values(infos)
            .join(" ")
    );
});

ip 第一部分是 0 或者 127 时不管错不错,直接忽略

当 ip 地址与掩码都存在错误时,只算一次

验证掩码是否合法255.0.1.0

255 的二进制是 11111111,总共 8 位,如果不足 8 位则要在前面补 0

0 的二进制 00000000

1 的二进制 00000001

合起来 11111111000000000000000100000000,不符合 1 的后面全是 0 的规则,除了用/^(1+)(0+)$/外,还可以通过lastIndexOf判断 1 是否在 0 前面

离职在家的 190 天

上一篇 下一篇

猜你喜欢

热点阅读