Reverse a number

In this exercise we will try to write code to reverse any number.

For this exercise we chose a random number to test our code with:

Example Input: 39582

Expected Output: 28593

First time I converted the number into a string, I used the split() method, then the reverse() method and the last time join() to bring it all together.

I named the function "reverse_a_number",  but it can have any name you want.

There are different ways to convert number to string :

  • String literal -> str = "" + num + "";
  • String constructor -> str = String(num);
  • toString -> str = num.toString();
  • String Literal simple -> str = "" + num;



=================================
HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Reverse a number</title>
<script src="javascript.js"></script>
</head>
<body>
  <p>Open console log!</p>
</body>
</html>

----------------------------------
JavaScript:

function reverse_a_number(n)
{
    n = n + "";
    return n.split("").reverse().join("");
}
console.log(Number(reverse_a_number(39528)));

=================================

Comments

Popular posts from this blog

How to set a minimum products number for an order in OpenCart v. 1.5.6.4

How to set a minimum price for an order in OpenCart v. 1.5.6.4