Problem: Given the summary, find the number of pages n the book has.
Example If the input is summary=25, then the output must be n=17: The numbers 1 to 17 have 25 digits in total: 1234567891011121314151617.
All inputs will be valid.
My current solution
function amountOfPages(summary){
let n=1; let arrKc=[1]
while((arrKc.join('').toString().length)!=summary){
arrKc.push( n.toString())
n
}
return n
}
All the tests passes but i get a timeout error as shown below
CodePudding user response:
Here is my code,
I see a pattern here to find the digits count
9 9 * 10 power 1 * 2 9 * 10 power 2 * 3 ... 9 * 10 power n-1 * n
My solution is based on the above pattern
function initialLoad() {
document.getElementById("outcome").innerHTML = "Answer: " amountOfPages(25);
}
function amountOfPages(summary) {
var n = summary;
var totalNumbersSoFar = 0;
var pagesSoFar = 0;
var ninthDigit = "9";
while (parseInt(ninthDigit) < (n / ninthDigit.length)) {
var numbersInRange = Math.pow(10, ninthDigit.length - 1) * 9;
pagesSoFar = numbersInRange * ninthDigit.length;
n -= numbersInRange;
totalNumbersSoFar = numbersInRange;
ninthDigit = "9";
};
return ((summary - pagesSoFar) / ninthDigit.length) totalNumbersSoFar;
};
<HTML>
<HEAD>
</HEAD>
<BODY id="outcome" onl oad="initialLoad()">
<h1>
</h1>
</BODY>
</HTML>