Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to write reverse number function using recursion in JavaScript

1 Answer

0 votes
<!DOCTYPE html>
<html>
<head>  
</head>
 
<body>
<p id="calc"></p>
<script>
function rev_num(n) 
{
    return n < 10 ? n : parseInt(n % 10) * Math.pow(10, _log10(n)) + rev_num(parseInt(n / 10));
}
function _log10(n) 
{
    return parseInt( Math.floor( (Math.log(n) / Math.LN10) ));
    //return parseInt( Math.floor( (Math.log(n) / Math.log(10)) ));
}
function print_rev_num(n)
{
    document.getElementById("calc").innerHTML =  rev_num(n);
}
</script>
<input type="button" value="rev_num(123)" onclick="print_rev_num(123)" />
<!--
    (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
         3     *     10 ^ 2 = 300       + rev_num(12)
         2     *     10 ^ 1 = 20        + rev_num(1)
         1     *     10 ^ 0 = 1         + rev_num(0)
         300 + 20 + 1 = 321; 
-->
<input type="button" value="rev_num(1234)" onclick="print_rev_num(1234)" />
<!--
    (n % 10) * pow(10, (int)log10(n)) + rev_num(n / 10);
         4     *     10 ^ 3 = 4000      + rev_num(123)
         3     *     10 ^ 2 = 300       + rev_num(12)
         2     *     10 ^ 1 = 20        + rev_num(1)
         1     *     10 ^ 0 = 1         + rev_num(0)
         4000 + 300 + 20 + 1 = 4321; 
-->
<input type="button" value="rev_num(1221)" onclick="print_rev_num(1221)" />


</body>
</html>

<!--
run:

321
4321
1221

-->

 



answered Dec 15, 2015 by avibootz

Related questions

2 answers 212 views
1 answer 139 views
1 answer 151 views
151 views asked Jan 16, 2021 by avibootz
1 answer 178 views
...