Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIJavascript Program to Count rotations which are divisible by 10

Javascript Program to Count rotations which are divisible by 10

Given a number N, the task is to count all the rotations of the given number which are divisible by 10.
Examples: 
 

Input: N = 10203 
Output:
Explanation: 
There are 5 rotations possible for the given number. They are: 02031, 20310, 03102, 31020, 10203 
Out of these rotations, only 20310 and 31020 are divisible by 10. So 2 is the output. 
Input: N = 135 
Output:
 

 

Naive Approach: The naive approach for this problem is to form all the possible rotations. It is known that for a number of size K, the number of possible rotations for this number N is K. Therefore, find all the rotations and for every rotation, check if the number is divisible by 10 or not. The time complexity for this approach is quadratic. 
Efficient Approach: The efficient approach lies behind the concept that in order to check whether a number is divisible by 10 or not, we simply check if the last digit is 0. So, the idea is to simply iterate over the given number and find the count of 0’s. If the count of 0’s is F, then clearly, F out of K rotations will have 0 at the end of the given number N
Below is the implementation of the above approach:
 

Javascript




<script>
 
// Javascript implementation to find the
// count of rotations which are
// divisible by 10
 
// Function to return the count of
// all the rotations which are
// divisible by 10.
function countRotation(n)
{
    let count = 0;
 
    // Loop to iterate through the
    // number
    do {
        let digit = n % 10;
 
        // If the last digit is 0,
        // then increment the count
        if (digit == 0)
            count++;
        n = parseInt(n / 10);
    } while (n != 0);
 
    return count;
}
 
// Driver code
let n = 10203;
document.write(countRotation(n));
 
</script>


Output: 

2

 

Time Complexity: O(log10N), where N is the length of the number.
Auxiliary Space: O(1)

Please refer complete article on Count rotations which are divisible by 10 for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Commit to GfG’s Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.

Last Updated :
31 Jul, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments