0
我需要使用長整數加上現在我已經創建了這個函數的字符串類型,但它會減慢... 任何人都知道更好的解決方案計算加字符串?PHP加上字符串類型
這裏是我的功能:
function math_plus($first, $second)
{
$first = strrev($first); $first_length = strlen($first);
$second = strrev($second); $second_length = strlen($second);
$result = "";
if ($first_length > $second_length)
{
$big = $first; $big_length = $first_length;
$small = $second; $small_length = $second_length;
}
else
{
$big = $second; $big_length = $second_length;
$small = $first; $small_length = $first_length;
}
$memory_exists = false;
for ($i=0;$i < $big_length;$i++)
{
$small_exists = ($i < $small_length)?true:false;
$big_value = (int) substr($big, $i, 1);
$value = $big_value;
if ($small_exists)
{
$small_value = (int) substr($small, $i, 1);
$value += $small_value;
}
if ($memory_exists){$value++;$memory_exists = false;}
if ($value >= 10){$value -= 10; $memory_exists = true;}
$result = $value . $result;
}
if ($memory_exists)
{
$result = "1" . $result;
}
return $result;
}
$first = "325436746798098576787634576587568764355645645654634645746657676543";
$second = "325436746798098576787634576587568764355645645654634645746657676543";
echo math_plus($first, $second);
不[此幫助(http://php.net/bcmath)? – vascowhite 2014-09-12 14:46:41
使用PHP的[bcmath](http://php.net/manual/en/function.bcadd.php)擴展 – 2014-09-12 14:46:45
這是功課嗎?如果它是作業,你應該告訴我們。我們仍然會幫助你,但這很公平。 – 2014-09-12 14:46:56