Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 99 题:编程算法题 #153

Open
yygmind opened this issue Jul 4, 2019 · 174 comments
Open

第 99 题:编程算法题 #153

yygmind opened this issue Jul 4, 2019 · 174 comments

Comments

@yygmind
Copy link
Contributor

yygmind commented Jul 4, 2019

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

@zh1989cool
Copy link

zh1989cool commented Jul 4, 2019

function fun(num){
    let num1 = num / 10;
    let num2 = num % 10;
    if(num1<1){
        return num;
    }else{
        num1 = Math.floor(num1)
        return `${num2}${fun(num1)}`
    }
}
var a = fun(12345)
console.log(a)
console.log(typeof a)

@dorseysen
Copy link

其实这种直接使用JavaScript的API更简单直观。

//  the first solution by recursion

const numToReverseStr = num => {

    if( 'number' !== typeof num ) throw '输入需为int型整数';

    if(!Math.floor(num / 10)) return num.toString();

    return (num % 10).toString() + numToReverseStr( Math.floor(num / 10) );
}

console.log(numToReverseStr(2169362));

//  the second solution not by recursion but JavaScript API

const numToReverseStr_0 = num => {

    return num.toString().split('').reverse().join('');
}

console.log(numToReverseStr_0(2169362));

@Gentlemancj
Copy link

`function test(num) {
var str = num + "";
if(str.length > 1) {
var newStr = str.substring(str.length - 1);
var oldStr = str.substring(0, str.length - 1);
return newStr + test(oldStr)
} else {
return num
}

}

var s = test(1234);

console.log(s);`

@lhj767382286
Copy link

lhj767382286 commented Jul 5, 2019

function test(num){
	num = typeof num === 'number' ? num.toString() : num
	if(num.length <= 1) return num
	else return num[num.length - 1] + test(num.substring(0, num.length - 1))
}

@TH-coder
Copy link

TH-coder commented Jul 5, 2019

function numberReverse(num) {
    const str = num.toString()
    return str.length === 1 ? str : numberReverse(str.substring(1)) + str.substring(0, 1)
}

这样行不,有错望指出

@huangxiaochang
Copy link

huangxiaochang commented Jul 5, 2019

function reverseNumber (num) {
if ((num / 10 >> 0) === 0) {
return (‘’ + num)
}
return ('' + num % 10 + reverseNumber(num / 10 >> 0) )
}
或者简化成三行代码
function reverseNumber (num) {
return (num / 10 >> 0) === 0 ? ('' + num) : ('' + num % 10 + reverseNumber(num / 10 >> 0) )
}

@kungithub
Copy link

function out(value){
  
 if(value.length===0) return '';
  
 value =  Array.isArray(value)?value:value.toString().split('');
 
  return value.pop() + out(value);

}

@mcDullLi
Copy link

mcDullLi commented Jul 5, 2019

function reverseInt(intNumber) {
if (!(intNumber%10)) {
return ''
}
return (intNumber%10).toString() + reverseInt(parseInt(intNumber/10))
}

@toufaluanle
Copy link

`var a = 1234;

function reverse(a){
var a = a.toString();
if(a.length==1){
return a
}else{
a = a.slice(-1)+reverse(a.slice(0,-1));
}
return a
}

reverse(a)`

@ch8839
Copy link

ch8839 commented Jul 5, 2019

思路:先将传入的参数转为string,取该字符串的第二位至末尾作为下一次递归函数的参数,判断当前字符串长度是否大于1,大于1则递归调用,等于1就返回这个字符串

function myReverse(num){ 
  let str = num.toString()
  let num2 = parseInt(str.slice(1))
  
  if(str.length >1){
    return myReverse(num2) + str[0]
  }else {
    return str
  } 
}

console.log(myReverse(1234))

@lhyt
Copy link

lhyt commented Jul 5, 2019

function reverse(num) {
  const str = `${num}`
  return str ? `${str % 10}${reverse(str.slice(0, str.length - 1))}` : ''
}

@yaonote
Copy link

yaonote commented Jul 5, 2019

image

@cjfff
Copy link

cjfff commented Jul 5, 2019

function renum(num) {
  num = num.toString()
  let rest = num.slice(0, -1),
    last = num.slice(-1);
  return last.length ? last + renum(rest) : ''
}

console.log(renum(12345678)); // 87654321

@bran-nie
Copy link

bran-nie commented Jul 5, 2019

如果能传两个参数的话,这个算法将会更好。
尾递归调用。性能上好不少。

function func(v, r = '') {
    v += ''
    if (v.length < 1) return r
    r += v.slice(v.length-1)
    v = v.slice(0, v.length-1)
    return func(v, r)

}
func(1234)
// "4321"

@YouziXR
Copy link

YouziXR commented Jul 5, 2019

如果能传两个参数的话,这个算法将会更好。
尾递归调用。性能上好不少。

function func(v, r = '') {
    v += ''
    if (v.length < 1) return r
    r += v.slice(v.length-1)
    v = v.slice(0, v.length-1)
    return func(v, r)

}
func(1234)
// "4321"

科里化一下就好了,在外面封装一层函数只接收参数v

@xuxchao
Copy link

xuxchao commented Jul 6, 2019

function fun(num){
    let num1 = num / 10;
    let num2 = num % 10;
    if(num1<1){
        return num;
    }else{
        num1 = Math.floor(num1)
        return `${num2}${fun(num1)}`
    }
}
var a = fun(12345)
console.log(a)
console.log(typeof a)

输入的数字小于 10 的时候返回的是整形

@momodiy
Copy link

momodiy commented Jul 6, 2019

const convert = num =>
   (num / 10) | 0
     ? String(num % 10) + convert((num / 10) | 0 )
     : String(num)

let res = convert(12345)
console.log(res) // 54321
console.log(typeof res)// string

@cycle07
Copy link

cycle07 commented Jul 7, 2019

const calc = nums => nums.toString().split('').reduce((sum, num) => num + sum);

@pengcc
Copy link

pengcc commented Jul 7, 2019

贴上两种方法

// es6
const reverse1 = (num) => [...num.toString()].reverse().join('');

// no variable
var intReverseRecursive = function intReverseRecursive(num) {
    if (typeof num === 'number') {
        // add an anchor at the end
        return intReverseRecursive((num + '#').split(''));
    } else {
        // stop recursive
        if (num.indexOf('#') === 0) {
            num.shift();
            return num.join('');
        } else {
            num.splice(num.indexOf('#'), 0, num.shift());
            return intReverseRecursive(num);
        }
    }
};

@zeybar
Copy link

zeybar commented Jul 8, 2019

function reverseNumber (num) {
if ((num / 10 >> 0) === 0) {
return (‘’ + num)
}
return ('' + num % 10 + reverseNumber(num / 10 >> 0) )
}
或者简化成三行代码
function reverseNumber (num) {
return (num / 10 >> 0) === 0 ? ('' + num) : ('' + num % 10 + reverseNumber(num / 10 >> 0) )
}

你这个不行
image

@5SSS
Copy link

5SSS commented Jul 8, 2019

function intToString (int) {
	if (int >= 10) {
		return String(int % 10) + intToString(Math.floor(int / 10))
	}
	return String(int)
}

@Zousdie
Copy link

Zousdie commented Jul 8, 2019

function doo (num) {
    const str = `${num}`;
    const temp = str.length > 2 ? doo(str.slice(1)) : str.slice(1);

    return `${temp}${str[0]}`
}

先转成字符串,然后根据长度递归调用

@86XIng
Copy link

86XIng commented Jul 8, 2019

const reverse = num=>
    num!=0 ? `${num % 10}${reverse(num / 10 >> 0)}` : ''

参考了各位大佬的思路,用%10来取最后一位,用/10来减少位数,用>>0来去除小数点,最后用es6的模板字符串来返回字符串类型的结果

@momodiy
Copy link

momodiy commented Jul 8, 2019

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

int型整数也包含负数,发现大多数解法(包括我的)都只考虑传入数值为正数的情况,题干中也没有相关示例,求解 @yygmind

@RanTing1992
Copy link

function fn1(num){
  var str = num.toString();
   let i = 0,newStr="";
   while(i<str.length){
      newStr+=str.slice(str.length-(i+1),str.length-i);
     i++
   }
return newStr;
}
fn1(1234)

@FounderIsShadowWalker
Copy link

var str = '12345';
function revert(str){
return str.length > 0 ? revert(str.slice(1)) + str[0] : str;
}

@feikerwu
Copy link

feikerwu commented Jul 9, 2019

function fun(num){
    let num1 = num / 10;
    let num2 = num % 10;
    if(num1<1){
        return num;
    }else{
        num1 = Math.floor(num1)
        return `${num2}${fun(num1)}`
    }
}
var a = fun(12345)
console.log(a)
console.log(typeof a)

我觉着这个还是得加一些异常case,比如1000,或者负数

/**
 * @case 1234 => '4321'
 * @case 1000 => '1'
 * @case -1000 => '-1'
 * @case -1234 => '-4321'
 *
 * @param {number} number 传入的数值
 */
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

  if (number < 10) {
    return `${number}`;
  }

  return `${number % 10 || ''}${solution(~~(number / 10))}`;
}

const assert = require('assert').strict;

assert.strictEqual(solution(1234), '4321');
assert.strictEqual(solution(1000), '1');
assert.strictEqual(solution(-1234), '-4321');
assert.strictEqual(solution(-1000), '-1');

@Weathers0086
Copy link

function reverseNum(x){
if(x<0){
return '-'+reverseNum(Math.abs(x))
}else if(typeof x === 'number'){
return reverseNum(String(x))
}
return x.length===0?x:reverseNum(x.slice(1)) + x[0]
}
reverseNum(1234560)
reverseNum(-1234560)

@FEJiuL
Copy link

FEJiuL commented Jul 9, 2019

	function main(num){
		let [n, str] = ('' + num / 10).split(".");
                 return n > 0 ? str + main(n) : str;
	}

@OhIAmFine
Copy link

OhIAmFine commented Apr 22, 2021

function reserveStr(num) {
  const str = num.toString(), len = str.length;
  if (len === 1 || !len) return str;
  if (len === 2) return str[1] + str[0];
  let res = "";
  for (let i = 0; i < len; i += 2) {
    res = reserveStr(str.slice(i, i + 2)) + res;
  }
  return res;
}

@peterczg
Copy link

peterczg commented May 4, 2021

function reverse(num){ return (num + "").length ? (reverse((num + "").slice(1)) + (num + "")[0]) : "" }

@MrLeihe
Copy link

MrLeihe commented May 11, 2021

function reverse(num) {
    // 得到个位数
    var mod = num % 10
    // 剩余位数
    var n = Math.floor(num / 10)
    if(n <= 0) {
        return num
    } else {
        return '' + mod + reverse(n) 
    }
}

@nxt-hj
Copy link

nxt-hj commented Jul 18, 2021

function toreverseString(int){
   if(!int&&int!==0) return ''
   var arr=int.toString().split('');
   var str = arr.pop()
   return str+toreverseString(arr.join(''))
}

@635864859
Copy link

function fun(num){
    let num1 = num / 10;
    let num2 = num % 10;
    if(num1<1){
        return num;
    }else{
        num1 = Math.floor(num1)
        return `${num2}${fun(num1)}`
    }
}
var a = fun(12345)
console.log(a)
console.log(typeof a)

输入的数字小于 10 的时候返回的是整形

小于10的时候toString()一下么

@printfshen
Copy link

function core(input) {
  input = (input + "")
  let length = input.length
  let count = length - 1
  let result = ""
  return function f1() {
    result += input[count]
    if (count <= 0) {
      count = length - 1
      return result
    }
    count--
    return f1.call(null)
  }
}

core(123456789)()  // 987654321

@iT-lijun
Copy link

iT-lijun commented Sep 15, 2021

这可能是不依赖任何API的最佳实践了吧
const reverseInt = num => (num/10 >> 0) ? `${num%10}${reverseInt(num/10 >> 0)}` : `${num}`

@lmfcz
Copy link

lmfcz commented Sep 23, 2021

// 用递归。第一步 处理递归到底的条件 第二步 构建一个更小问题的解。 第三步 用更小问题的解构建出原问题的解
第一步 很明显
第二步 reverse这个函数的宏观语意就是题目的意思,输入一个整数 返回 这个整数的逆序字符串。 那么将原num % 10 后得到一个子整数即新的num reverse(num)就很明确的求出了原数字 除了 个位的逆序数
第三步 将个位数与 reverse(num) 加起来 构建原问题的解
const reverse = (num: number): string => {
if (num < 10) {
return num.toString()
}
const cur = (num % 10).toString()
num = Math.floor(num / 10)
return cur + reverse(num)
}

@ganbowengo
Copy link

function numberToString(num) {
let a = num % 10
let b = Math.floor(num/10)
if(b === 0) return a
return a + '' + numberToString(b)
}

@xiangfei1
Copy link

function numToString(num, res = []) {
	if (num == '') return;
		let temp = Number(num) % 10;
		res.push(temp);
		let str = num.toString();
		if (res.length !== 0) {
			numToString(str.slice(0, -1), res)
		}
	return res.join('');
}

@zhangtaolei
Copy link

function reverse(num){
   if(num < 10) return num
   let str = ''
   str = `${num%10}${reverse(Math.floor(num/10))}`
  return str
 }

@toSeeWorld
Copy link

function reverse(val) {
if (!val) return ''
let str = val + ''
return reverse(+str.slice(1)) + str.charAt(0)
}

@dymic-web
Copy link

function reverse(num){
    var str=String(num)
    if(str.length===1){
        return str
    }

    return  reverse(str.slice(-1))+reverse(str.slice(0,-1))

}

@Four-Names
Copy link

function fun(int, x = int.toString().split(""), y = "") {
  if (x.length == 0) return y;
  else y = fun(undefined, x, x.shift()) + y;
  return y;
}
console.time("my");
console.log(fun(123212312312312313212312123321231231231));
console.timeEnd("my");

console.time("sys");
console.log(
  (123212312312312313212312123321231231231)
    .toString()
    .split("")
    .reverse()
    .join("")
);
console.timeEnd("sys");

@liushan-github
Copy link

function getRevString(num){
let numString= typeof num == 'string' ? num : num.toString();
if(numString<=1){
return numString
}else{
return ${numString.slice(numString.length- 1)}${getRevString(numString.slice(0,numString.length-1))}
}

}
console.log(getRevString(1234))

@DearICE
Copy link

DearICE commented Mar 14, 2022

function reverseN2S(num) {
  let str = num + '';
  let index = str.length - 1;
  return str[index] + (index > 0 ? reverseN2S(str.substring(0, index)) : '');
}

console.log(reverseN2S(1234));    // '4321'
console.log(reverseN2S(-1000));   // '0001-'

@karl-barkmann
Copy link

karl-barkmann commented Mar 24, 2022

function input(num){
    const str = num.toString();
    function reverser(pos){
        if(pos<0){
            return '';
        }
        return str.charAt(pos)+reverser(--pos);
    }
    return reverser(str.length-1);
}

@Twlig
Copy link

Twlig commented Apr 13, 2022

function reverse(num) {
    if(num == undefined) {
        return
    }
    var str = num + ''
    if(str.length == 0) {
        return str
    }
    var s = str.charAt(str.length - 1)
    return s + reverse(str.substr(0, str.length - 1))
}

@Margaux7
Copy link

function reverse(num) {
    num = typeof num === 'number' ? '' + num : num;
    if (!num.length) return '';
    
    return num.slice(-1) + reverse(num.slice(0, -1));
}

@johnsoncheg
Copy link

function input(num) {
	const strNum = String(num)
    
	if (strNum.length === 1) return strNum

	const d = Math.pow(10, strNum.length - 1)
	const res = Math.floor(num / d)
	const left = num % d
    
    console.log('res', res)
    console.log('d', d)
	return input(left) + res + ''
}

console.log(input(1234)) // '4321'

@ShopkeeperEgg
Copy link

function solve(int) {
  if (int === 0) return '';
  const tar = int % 10;
  // 如果可以不可以用Math
  // return tar.toString() + solve(int / 10 - int / 10 % 1);
  // 如果可以用parseInt
  return tar.toString() + solve(parseInt(int / 10));
}

@FrankyYang
Copy link

代码:const print = (num) => num < 10 ? '' + num : num % 10 + print(parseInt(num / 10))
测试:print(1234)

@XW666
Copy link

XW666 commented Aug 22, 2022

//方式一
function numberReverse(num) {
    let m = num.toString().split(',')
    let res = []
    //递归
    let fun = function (list) {
      if (list.length > 0) {
        res.push(list.pop())
        fun(list)
      }
    }
    fun(m)
    return Number(res.join(''))
  }
//方式二
 var reverse = function (x) {
    let rev = 0;
    //方式二:递归的形式
    function fun(num) {
      if (num !== 0) {
        let num2 = num % 10;
        rev = rev * 10 + num2;
        //~~:去掉小数部分
        let num1 = ~~(num / 10);
        fun(num1)
      }
    }
    fun(x)
    return rev
  };

@xuhen
Copy link

xuhen commented Nov 30, 2022

function convert(n) {
    const str = n.toString();
    const helper = (s, i) => {
        if (i === s.length) return '';
        return helper(s, i + 1) + s[i];
    }
    return helper(str, 0);
}

@ElderlyBoy
Copy link

ElderlyBoy commented Jan 14, 2023

function fun(num){
    let num1 = num / 10;
    let num2 = num % 10;
    if(num1<1){
        return num;
    }else{
        num1 = Math.floor(num1)
        return `${num2}${fun(num1)}`
    }
}
var a = fun(12345)
console.log(a)
console.log(typeof a)

fun(1)// 1 number

@benzhemin
Copy link

const reverseToString = (value, res = []) => {
    if (value > 0) {
        const digital = value % 10;
        res.push(digital);
        return reverseToString(Math.floor(value / 10), res);
    }
    return res.join('');
}

const res = reverseToString(1234);

console.log(res);

@qifengla
Copy link

qifengla commented Jun 2, 2023

function reverseInteger(num) {
  if (num < 10) {
    return num.toString();
  }
  
  const lastDigit = num % 10;
  const remainingDigits = Math.floor(num / 10);
  
  return lastDigit.toString() + reverseInteger(remainingDigits);
}

@Dylan0916
Copy link

Dylan0916 commented Aug 25, 2023

function func(num) {
  const str = num + '';

  if (str.length === 1) {
    return str;
  }

  const newStr = str.slice(-1);
  const remainingStr = str.slice(0, -1);

  return newStr + func(remainingStr);
}

@shawon1220
Copy link

(1234).toString().split('').reverse().join('')

@Feng-K3
Copy link

Feng-K3 commented Apr 9, 2024

其实就是一个整数反转啦

const reverse = (num) => {
    let res = 0;
    while (num) {
      res = res * 10 + (num % 10)
      num = ~~(num / 10) // 取整数
    }
    return res + ''; // 最后强转 String 类型
};
reverse(12345)  // '54321'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests