D29_第三週作業


Posted by Christy on 2021-05-17

hw4:判斷迴文

  • 我覺得我跟 OJ 的輸入還沒有變成好朋友...
var readline = require('readline');

var lines = []
var rl = readline.createInterface({
  input: process.stdin
});

rl.on('line', function (line) {
  lines.push(line)
});

rl.on('close', function() {
  solve(lines)
})

function solve(lines) {
    let str = lines[0]
    if(Palindrome(str)===str) {
        console.log('True')
    } else {
        console.log('False')
    }
}

function Palindrome(str) {
    let result = ''
    for(let i=str.length - 1; i>=0; i--) {
        result += str[i]    
    }
    return result
}

hw3:判斷質數

  • 解這題的時候,最後卡在沒有把資料轉成數字,所以一直不過。
  • 另外我沒有想到比較漂亮的三元運算子的寫法:
function solve(lines){
  for(let i=1; i<lines.length; i++) {
    console.log(isPrime(Number(lines[i])) ? 'Prime' : 'Composite')
  }
}
  • 我的解法
var readline = require('readline');

var lines = []
var rl = readline.createInterface({
  input: process.stdin
});

rl.on('line', function (line) {
  lines.push(line)
});

rl.on('close', function() {
  solve(lines)
})

function solve(lines) {
    for(let i=1; i<lines.length; i++) {
        if(isPrime(Number(lines[i]))) {
            console.log('Prime')
        } else {
            console.log('Composite')
        }
    }
}

function isPrime(n) {
    if(n === 1) {
        return false
    }

    for(let i=2; i<n; i++) {
        if(n % i === 0) {
            return false
        }
    }
    return true
}

hw2:水仙花數

var readline = require('readline');

var lines = []
var rl = readline.createInterface({
  input: process.stdin
});

rl.on('line', function (line) {
  lines.push(line)
});

rl.on('close', function() {
  solve(lines)
})

function solve(lines) {
    let data = lines[0].split(' ')
    for(let i=Number(data[0]); i<=Number(data[1]); i++) {
        if(isNarcissistic(i)) {
            console.log(i)
        }
    }
}

function isNarcissistic(n) {
    let str = n + ''
    let digits = str.length
    let ans = 0
    for(let i=0; i<str.length; i++) {
        ans += Number(str[i])**digits
    }
    return ans === n     
}

hw5:聯誼順序比大小

  • 下面是一開始解題想法,但是是錯的
var readline = require('readline');

var lines = []
var rl = readline.createInterface({
  input: process.stdin
});

rl.on('line', function (line) {
  lines.push(line)
});

rl.on('close', function() {
  solve(lines)
})

function solve(lines) {
    for(let i=1; i<lines.length; i++) {
        let temp = lines[i].split(' ')
        let A = Number(temp[0])
        let B = Number(temp[1])

        if(Number(temp[2]) === 1 && A>B) {
            console.log('A')
        } else console.log('B')

        if(Number(temp[2]) === -1 && A<B) {
            console.log('A')
        } else console.log('B')

        if(A === B) {
            console.log('DRAW')
        }
    }
}









Related Posts

MTR04_0908

MTR04_0908

演習課 WEEK14 (部屬)

演習課 WEEK14 (部屬)

個人CodeBase紀錄 - EP.1 先來加入類別庫 真酷

個人CodeBase紀錄 - EP.1 先來加入類別庫 真酷


Comments