Skip to content

Instantly share code, notes, and snippets.

@geekdreamzz
Last active December 22, 2015 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekdreamzz/6530018 to your computer and use it in GitHub Desktop.
Save geekdreamzz/6530018 to your computer and use it in GitHub Desktop.
If given integer N and computing from 0 to N, and counting the number of times an integer appears containing a "5". What would be your best solution? Here's what I got. Included in this html document is a web form and some javascript.
<HTML>
<HEAD>
<SCRIPT language=Javascript>
//only accept numeric values in input box
function isNumeric(num)
{
var charCode = (num.which) ? num.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
return true;
}
//given n calculate how many iterations of numbers containing integer 5 is in the range of 0 to n
function calculateDigitRange()
{
var n = document.forms["form"]["input"].value;
var five_counter = 0
for (var i=0;i <= (parseInt(n) + 1) ;i++)
{
if (i == (parseInt(n) + 1))
{
var show = "You gave me the number " + n + "<br><br> I counted from 0 to " + n + "<br><br>and I found numbers containing the integer 5... " + five_counter + " times!"
document.getElementById("answer").innerHTML=show;
break;
}
if (String(i).match(/[5]/) != null)
{
five_counter++;
continue;
}
}
}
</SCRIPT>
<style>
#container {margin:auto; width: 800px; padding-top: 60px;text-align: center;}
.center {text-align: center;}
</style>
</HEAD>
<BODY >
<div id="container">
<h1>Integer 5 Counter</h1>
<p>Enter a number, I'll count to it from 0, and I'll show you how many times a "5" appears</p>
<form id="form">
<INPUT id="input" class="center" onKeyPress="return isNumeric(event)" type="text" maxlength="7">
<br>
<INPUT TYPE="button" VALUE="Enter a number!" onClick="calculateDigitRange()">
</form>
<p id="answer"></p>
</div>
</BODY>
</HTML>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment