코딩 테스트/알고리즘 공부

가장 큰 자리 숫자 남기고 내림

fullfish 2023. 5. 4. 17:19
let numArr = [0, 3, 34, 345, '/', 0.3, 0.34, 0.345, ',', 0.03, 0.034, 0.0345, 0.00345]
numArr.forEach(e => {
  let regex = new RegExp(`(?<!0)(?<=[\\d*])\\d|-*(\\.0*)*\\d$`, 'g')
  console.log(parseFloat(String(e).replace(regex, '0')), parseFloat(String(-e).replace(regex, '0')))
})
let numArr = [98.57, 98.07, 100.1, 100.01, 7.5, 100, 3, 34, 345, 0.3, 0.34, 0.345, 0.03, 0.034, 0.0345, 0.003, 0.0034, 0.00345]
function js(num) {
  if (num <= 0) return num
  let str = String(num)
  if (str.match(/[1-9]/g).length === 1) return 0
  else if (/\./.test(str)) {
    const int = str.match(/\d+(?=\.)/)[0]
    if (int === '0') {
      let index = str.match(/[1-9]/).index
      index -= 1
      return Math.floor(num * 10 ** index) / 10 ** index
    } else {
      let intLen = int.length
      intLen -= 1
      return Math.floor(num / 10 ** intLen) * 10 ** intLen
    }
  } else {
    let len = str.length - 1
    return Math.floor(num / 10 ** len) * 10 ** len
  }
}
numArr.forEach(e => console.log(`${e} => ${js(e)}`))

'코딩 테스트 > 알고리즘 공부' 카테고리의 다른 글

숫자와 문자가 섞인 문자열 배열 정렬  (0) 2023.06.22
stirling formula(팩토리얼)  (0) 2023.03.26
Tree  (0) 2023.02.06
팩토리얼 factorial  (0) 2022.12.25
순열, 중복순열, 조합, 중복조합  (0) 2022.12.25