مساله:
با توجه به رشته ای از ارقام ، باید هر رقم زیر 5 را با ‘0’ و هر رقم 5 و بالاتر را با ‘1’ جایگزین کنید. رشته به دست آمده را برگردانید.
Description:
Given a string of digits, you should replace any digit below 5 with ‘0’ and any digit 5 and above with ‘1’. Return the resulting string.
public class FakeBinary { public static String fakeBin(String numberString) { return numberString.replaceAll("[0-4]", "0").replaceAll("[5-9]", "1"); } }
import java.util.Arrays; import java.util.stream.Collectors; public class FakeBinary { public static String fakeBin(String numberString) { if (numberString == null || numberString.length() == 0) return ""; return Arrays.stream(numberString.split("")).map(s -> {return Integer.parseInt(s) < 5 ? "0" : "1";}).collect(Collectors.joining()); } }
public class FakeBinary { public static String fakeBin(String s) { return s.replaceAll("[1-4]","0").replaceAll("[^0]","1"); } }
import static java.util.stream.Collectors.joining; public class FakeBinary { public static String fakeBin(String str) { return str.chars().mapToObj(c -> c < '5' ? "0" : "1").collect(joining()); } }
import java.util.stream.Collectors; public class FakeBinary { public static String fakeBin(String numberString) { return numberString.chars() .mapToObj(x -> String.valueOf((Character.getNumericValue(x) < 5) ? 0 : 1)) .collect(Collectors.joining()); } }
function fake_bin(string $s): string { return preg_replace(array('/[0-4]/', '/[5-9]/'), array('0', '1'), $s); }
function fake_bin(string $s): string { return strtr($s, '0123456789', '0000011111'); }
function fake_bin(string $s): string { $s = str_replace(range(0,4), 0, $s); $s = str_replace(range(5,9), 1, $s); return $s; }
function fake_bin(string $s): string { $result = ""; foreach (str_split($s) as $char) if ((int)$char < 5) $result = $result . '0'; else $result = $result . '1'; return $result; }