Git Product home page Git Product logo

Comments (1)

MY729 avatar MY729 commented on July 19, 2024

偶然看到跟这个题类似的一道题,参考它的解法有了新的思路

题目

用 JavaScript 写一个函数,输入 int 型,返回整数逆序后的字符串。如:输入整型 1234,返回字符串“4321”。要求必须使用递归函数调用,不能用全局变量,输入函数必须只有一个参数传入,必须返回字符串

答案

let reverseNum = (num) => {
  let intNum = Math.floor(num / 10)
  let samllNum = num % 10
  if (intNum < 1) {
    return num
  } else {
    return `${samllNum}${reverseNum(intNum)}`
  }
}

reverseNum(1234567) // 调用

// 输出
“7654321”

这个题的输出是一个字符串,并且用到了模板字符串语法

如果要输出Number类型 ,只要处理输出的字符串为数字类型就可以啦

let reverseNum = (num) => {
  let intNum = Math.floor(num / 10)
  let samllNum = num % 10
  if (intNum < 1) {
    return num
  } else {
    return Number(`${samllNum}${reverseNum(intNum)}`)
  }
}

reverseNum(1234567) // 调用

// 输出
7654321

from algorithm.

Related Issues (10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.