题意:给出字符串,去除重复的字符,计算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);