'Codility - CountDiv JavaScript solution
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
Solution 1:[1]
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;
}
Solution 2:[2]
My first attempt was to make it this way:
function solution(A, B, K) {
return Math.floor(B / K) - Math.floor(A / K) + (A % K === 0 ? 1 : 0);
}
and it scores 100/100, as it was mentioned parseInt should do the trick as well.
Solution 3:[3]
Swift 100%
public func solution(_ A : Int, _ B : Int, _ K : Int) -> Int {
// write your code in Swift 4.2.1 (Linux)
let offset = A % K == 0 ? 1 : 0
return (B/K) - (A/K) + offset
}
Solution 4:[4]
function solution(A, B, K) {
return Math.floor(B / K) - Math.ceil(A / K) + 1;
}
Score 100/100
Solution 5:[5]
function solution(A, B, K) {
// write your code in JavaScript (Node.js 8.9.4)
let val;
if(A % K === 0 || B % K === 0) {
val = Math.floor(((B - A)/K + 1));
} else {
let x = A % K;
let y = B % K;
val = ((B - A) + (x - y))/K
}
if((B === A) && (B === K)) {
val = Math.floor(((B - A)/K + 1));
}
return val;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Andrzej Czerwoniec |
Solution 3 | Pushpendra Singh |
Solution 4 | Arup Nayak |
Solution 5 | Ankit Vashishta |