Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Pre každé číslo v zadanom intervale od i
do j
spočítaj koľko je takých zadaných čísel, ktoré splnia zadanú podmienku.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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) } |
Ruby
1 2 3 4 5 6 7 8 9 |
(s, e, d) = gets.strip.split.map(&:to_i) count = 0 for i in s..e do reversed = i.to_s.reverse count += 1 if (i - reversed.to_i).abs % d == 0 end puts count |