Hackerrank – Problem Statement A description of the problem can be found on Hackerrank. Solution For each number in the given interval between i and j count the numbers with valid given condition. I created solution in: Scala Java JavaScript Ruby All solutions are also available on my GitHub. Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int start = stdin.nextInt(); int end = stdin.nextInt(); int k = stdin.nextInt(); int count = 0; for(int i = start; i <= end; i++) { String s = String.valueOf(i); String reversed = new StringBuilder(s).reverse().toString(); int diff = Math.abs(Integer.parseInt(s) - Integer.parseInt(reversed)); if(diff % k == 0) { count++; } } System.out.println(count); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
'use strict'; const reverse = (s) => s.split("").reverse().join(""); const processData = input => { const [start, end, d] = input.split(' ').map(i => parseInt(i)); let count = 0; for(let i = start; i <= end; i++) { const s = i.toString(); const reversed = reverse(s); const diff = Math.abs(parseInt(s) - parseInt(reversed)); if(diff % d == 0) { count++; } } console.log(count); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
|
import scala.io.Source object BeautifulDaysAtTheMovies extends App { val nums = Source.stdin.bufferedReader().readLine().split(" ").map(_.toInt) val start = nums(0) val end = nums(1) val d = nums(2) val beautifulNum = (start to end).count(num => { val reversed = num.toString.reverse.toInt val diff = (num - reversed).abs diff % d == 0 }) println(beautifulNum) } |
[…]