I remembered one task, I need to write a function, I return the number in the reverse order, without converting it to a string. For example, 5921 -> 1295. It won’t work out how to do it.

Closed due to the fact that off-topic participants are Visman , Kromster , Yaroslav Molchan , Alexey Shimansky , aleksandr barakin Jun 8 '17 at 8:28 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The message contains only the text of the task, in which there is no description of the problem, or the question is purely formal (" how do I do this task ") . To reopen the question, add a description of the specific problem, explain what does not work, what you see the problem. " - Visman, Kromster, Yaroslav Molchan, Alexey Shimansky, aleksandr barakin
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • recursion or cycle - Grundy

5 answers 5

And so satisfied with the answer? without conversion to string :

 var x = 5921; var y = 0; for(; x; x = Math.floor(x / 10)) { y *= 10; y += x % 10; } console.log(y); 

    While num !== 0 we take the last digit from num , divide this num by 10, add the order to the result and add the last digit to the result .

     var num = 5921; function getReversedNum(num) { let result = 0; while (num) { result = result * 10 + num % 10; num = Math.floor(num / 10); } return result; } console.log(getReversedNum(num)); 

    • Better than my version) - Darth

    Not the best option, but working:

     function reverseInt(number) { var result = ''; while(number>0){ result = result + (number%10); number = parseInt(number/10); } return result; } var number = 5921; console.log(reverseInt(number)); 

    • There is a string conversion. - Alexey Ten

     revert = num => { let i = 0, result=0; for(let r=1; r<num; r=10**++i) result+=(((num-num%r)/r)%10)/r; return result*(10**(i-1)); } console.log([321,48735,90008].map(revert)) 

      Or so:

       function reverse(num, r = 0){ if(!num) return r; r = r * 10 + num % 10; return reverse(Math.floor( num / 10), r); } console.log(reverse(12345)); 

      • without conversion to string - Grundy
      • @Grundy did not see - Sv__t
      • You can remove the ternary operator (r ? r * 10 : 0) using the default parameter value: function reverse(num, r=0){ - Grundy
      • @Grundy, fixed, thanks! - Sv__t