Advanced-Frontend / Daily-Interview-Question

我是依扬(木易杨),公众号「高级前端进阶」作者,每天搞定一道前端大厂面试题,祝大家天天进步,一年后会看到不一样的自己。
https://muyiy.cn/question/
27.42k stars 3.29k forks source link

第 99 题:编程算法题 #153

Open yygmind opened 5 years ago

yygmind commented 5 years ago

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

zh1989cool commented 5 years ago
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 commented 5 years ago

其实这种直接使用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 commented 5 years ago

`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 commented 5 years ago
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 commented 5 years ago
function numberReverse(num) {
    const str = num.toString()
    return str.length === 1 ? str : numberReverse(str.substring(1)) + str.substring(0, 1)
}

这样行不,有错望指出

huangxiaochang commented 5 years ago

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 commented 5 years ago

function out(value){

 if(value.length===0) return '';

 value =  Array.isArray(value)?value:value.toString().split('');

  return value.pop() + out(value);

}
mcDullLi commented 5 years ago
function reverseInt(intNumber) {
if (!(intNumber%10)) {
return ''
}
return (intNumber%10).toString() + reverseInt(parseInt(intNumber/10))
}
toufaluanle commented 5 years ago

`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 commented 5 years ago

思路:先将传入的参数转为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 commented 5 years ago
function reverse(num) {
  const str = `${num}`
  return str ? `${str % 10}${reverse(str.slice(0, str.length - 1))}` : ''
}
yaonote commented 5 years ago

image

cjfff commented 5 years ago
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 commented 5 years ago

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

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 commented 5 years ago

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

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 commented 5 years ago
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 commented 5 years ago
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 commented 5 years ago

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

pengcc commented 5 years ago

贴上两种方法

// 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 commented 5 years ago

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 commented 5 years ago
function intToString (int) {
    if (int >= 10) {
        return String(int % 10) + intToString(Math.floor(int / 10))
    }
    return String(int)
}
Zousdie commented 5 years ago
function doo (num) {
    const str = `${num}`;
    const temp = str.length > 2 ? doo(str.slice(1)) : str.slice(1);

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

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

86XIng commented 5 years ago
const reverse = num=>
    num!=0 ? `${num % 10}${reverse(num / 10 >> 0)}` : ''

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

momodiy commented 5 years ago

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

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

RanTing1992 commented 5 years ago
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 commented 5 years ago

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

feikerwu commented 5 years ago
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 commented 5 years ago
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 commented 5 years ago
    function main(num){
        let [n, str] = ('' + num / 10).split(".");
                 return n > 0 ? str + main(n) : str;
    }
JerryWang1996 commented 5 years ago

题目很简单,增加一些异常判断好了

const reverse = (num) => {
  let type = num || undefined;
  if(Object.prototype.toString.call(type) !== '[object Number]') {
    return;
  }
  if(num < 0) {
    return '-' + reverse(num * -1)
  }
  let s = num + '';
  if(s.length > 1){
    let temp = s.substring(0,1);
    num = s.substring(1,s.length) - '';
    return reverse(num) + temp;
  }else {
    return num + '';
  }
}
mongonice commented 5 years ago

function reverse (num) {

  num = typeof num  === 'number' ? num.toString() : num;

  if (num.length <= 1) return num;

  return `${num[num.length-1]}${reverse(num.slice(0, -1))}`

}
zhengjianghao commented 5 years ago

var reverse = function(n) { n = n + ''; return Array.from(n).reduce((str, a) => { return a + str; }) }

LiuMengzhou commented 5 years ago

恕我直言

function print(n) {
  if (!n) return '0';
  let num2Str = n => {
    if (!n) return '';
    return `${n % 10}` + num2Str(~~(n / 10));
  }
  return num2Str(n);
}
Riteam commented 5 years ago

INT范围内不会有问题😊

function revNum(num){
  if(num < 10){
    return '' + num
  } else return '' + num%10 + revNum(num/10>>0)
}
ryhnatwoods commented 5 years ago

function reverseStr(num) { if (num < 10) { return num; }

let res = (num % 10) + "" + reverseStr(Math.floor(num / 10)); return res; }

wonder0721 commented 5 years ago

function foo(num){ if(typeof(num) == 'number'){ var a = num.toString(); var b = []; for (var i = a.length - 1; i >= 0; i--){ b.push(a[i]); } return foo(b); } return num.join(''); }

Renser804 commented 5 years ago

function sortNum2String(num){ let arr = (num+'').split(''); arr.sort((a,b)=>{ return b-a }) return arr.join('') }

Drakes-0 commented 5 years ago

function sortNum2String(num){ let arr = (num+'').split(''); arr.sort((a,b)=>{ return b-a }) return arr.join('') }

???

11341684 commented 5 years ago
// 使用递归,只使用一个参数(利用柯里化)
function reverse(index) {
    return function (num) {
        num=num+'';
        if(index>=num.length/2||(index>=num.length/2-1&&num.length%2===1))return num;
        return reverse(index+1)(num.slice(0,index)+num[num.length-1-index]+num.slice(index+1,-index-1)+num[index]+(index!==0?num.slice(-index):''))
    }
}
reverse(0)(123456);
bgwd666 commented 5 years ago

function bili(int){ if(int.toString().length <= 1){ return int } return (int/10).toString().slice(-1) + bili(parseInt(int/10)) }

atheist1 commented 5 years ago
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

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

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

我觉得这样才是正解,不考虑负数和倒过来是0就像耍流氓

atheist1 commented 5 years ago
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

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

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

测试了下,跟我的bug一样。1001的中间0都被Number化时去除了

feikerwu commented 5 years ago
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

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

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

测试了下,跟我的bug一样。1001的中间0都被Number化时去除了

单参就比较难了,双参的话就比较好写,用一个参数带初始number的位数信息,在去掉0的时候判断一下就行

atheist1 commented 5 years ago
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

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

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

测试了下,跟我的bug一样。1001的中间0都被Number化时去除了

单参就比较难了,双参的话就比较好写,用一个参数带初始number的位数信息,在去掉0的时候判断一下就行

我觉得这才是这道题的难点,要不然不考虑这些真的是在耍流氓。。

Jean1024 commented 5 years ago
function reverse(num){
  num = num + ''
  var len = num.length
  if(len == 1) return num
  return num[len - 1] + reverse(num.slice(0,-1))
}

console.log(reverse(1234))
MasonEast commented 5 years ago

function reverse(num){ return num.toString().split('').reverse().join('') }

feikerwu commented 5 years ago
function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

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

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

测试了下,跟我的bug一样。1001的中间0都被Number化时去除了

单参就比较难了,双参的话就比较好写,用一个参数带初始number的位数信息,在去掉0的时候判断一下就行

我觉得这才是这道题的难点,要不然不考虑这些真的是在耍流氓。。

用小数位来标示是否舍0,写的很复杂,暂时符合条件了。。

function solution(number) {
  if (number < 0) {
    return `-${solution(Math.abs(number))}`;
  }

  let integerPart = Math.floor(number);
  let decimal = `${number}`.split('.')[1];

  let numberSize = `${integerPart}`.length;

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

  if (integerPart % 10 === 0) {
    let initialNumberSize = decimal || 0;
    // initialNumberSize === 0 => 初始number以0为结尾
    // +initialNumberSize === numberSize => 以2个以上0为结尾
    if (initialNumberSize === 0 || +initialNumberSize === numberSize) {
      return solution(parseFloat(`${~~(integerPart / 10)}.${numberSize - 1}`));
    }
    return `0${solution(
      parseFloat(`${~~(integerPart / 10)}.${initialNumberSize}`)
    )}`;
  }

  // 以小数标示从首位到最后一位非0位置的个数
  return `${integerPart % 10}${solution(
    parseFloat(`${~~(integerPart / 10)}.${decimal || numberSize}`)
  )}`;
}

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');
assert.strictEqual(solution(1011), '1101');
assert.strictEqual(solution(-1001), '-1001');
MKLM0222 commented 5 years ago
function transformwrap(n){
  var sum=""
  function transform(n){
    if(n<=0){
      return sum
    }
    var left=n%10
    sum+=left
    n=(n-left)/10
    transform(n)
  }
  transform(n)
  return sum
}
yaoqifa commented 5 years ago
function reverse(num) {
  if (num < 0) {
    return `-${reverse(Math.abs(num))}`
  }
  if (num < 10) {
    return num;
  }
  return `${num % 10}${reverse(Math.floor(num / 10))}`
}

test: reverse(123349495) "594943321" reverse(-123455) "-554321" reverse(-1234000055) "-5500004321" reverse(-12340000500005) "-50000500004321"

young122849 commented 5 years ago

function itoa (num) { return (num % 10 === 0 ? "" : num % 10) + (num >= 10 ? itoa(parseInt(num / 10)) : ""); }