Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codility - CountDiv JavaScript solution

Tags:

javascript

I'm still a bit new to JavaScript so if anyone care to explain how to solve this small issue.

Basically, i'm using different languages to solve codility training tasks. I've encountered small problem when working with java script, floating points. Here is the example of what I mean. Task in question is in Lesson 3, task one: CountDiv

In Java my solution works perfectly it scored 100/100. Here is the code:

class Solution {
    public int solution(int A, int B, int K) {

        int offset = A % K ==0?1:0;

        return (B/K) - (A/K) + offset;

    }
}

Written in java script code scores 75/100.

function solution(A, B, K) {
   var offset;

   if (A % K === 0) {
       offset=1;
   } else {
       offset=0;
   }

   var result =(B/K) - (A/K) + offset;

   return parseInt(result);
}

JavaScript solution fails on following test: A = 11, B = 345, K = 17 (Returns 19, Expects 20)

I'm assuming that its something to do with how JavaScript convert floating point to Integers ?

If anyone care to explain how to write JS solution properly?

Thanks

like image 382
Bola Avatar asked Dec 14 '22 11:12

Bola


1 Answers

Use parseInt on the division result.

When you use division operator, the result is coerced to floating point number, to make it integer use parseInt on it. (Thanks to @ahmacleod)

function solution(A, B, K) {
    var offset = A % K === 0 ? 1 : 0;
    return parseInt(B / K) - parseInt(A / K) + offset;
}
like image 165
Tushar Avatar answered Dec 29 '22 18:12

Tushar