spoj String To Binary(數字轉二進位制、讀取數字和字串)
阿新 • • 發佈:2019-01-05
題意:給出字串,去除重複的字元,計算ascii的和,將其轉換成二進位制數顯示
程式碼如下:
<?php function readInt($file) { while (false !== ($ch = fgetc($file))) { if (preg_match('/[[:digit:]]/', $ch)) break; } $sum = ord($ch) - ord('0'); while (false !== ($ch = fgetc($file))) { if (!preg_match('/[[:digit:]]/', $ch)) break; $sum = $sum * 10 + (ord($ch) - ord('0')); } return $sum; } function readStr($file) { while (false !== ($ch = fgetc($file))) { if (!preg_match('/[[:space:]]/', $ch)) break; } $sum = $ch; while (false !== ($ch = fgetc($file))) { if (preg_match('/[[:space:]]/', $ch)) break; $sum = $sum.$ch; } return $sum; } function numberToBinary($s) { if ($s == 0 ) return ''; else { return numberToBinary(floor($s / 2)).($s % 2); } } $debug = true; $file = STDIN; if ($debug) $file = fopen('./test.txt', 'r'); $t = readInt($file); for ($i = 1; $i <= $t; $i++) { $s = readStr($file); $sum = 0; $set = array(); for ($j = 0; $j < strlen($s); $j++) { if (!in_array($s[$j], $set)) { $sum += ord($s[$j]); $set[] = $s[$j]; } } $ans = numberToBinary($sum); printf("#%d : %s\n", $i, $ans); } if ($debug) fclose($file);