I have this algorithm written in PHP for my project:
<?php
$s = "abc"; //input -- string
$n = strlen($s);
$b = 0;
for ($i = 0; $i < $n; $i++)
{
$b += ord($s[$i]) * pow(31, ($n - ($i + 1)));
}
echo $b; //output -- int
?>
But now I have to reverse it to take the string from integer. I tried but it failed, is there any way to reverse it?
EDIT: By “any way” I meant that it doesn’t have to reverse to the original text, but only to reverse to text that gives that value.
IF the string can be guaranteed to only have lowercase letters on it, it can; you’ll have to figure out the maths for it (I suggest you work out in paper the algorithm, leaving the letters as variables; solve the equations and you’ll see how to reverse it).
If the string is arbitrary, then no; because you’re converting each character to a base-31 representation of the number, shifting it and adding the results — however, this addition has lots of carries, so you can’t work out the original characters just from the digits (that is, the final number) of the result.
EDIT: given your edit, then yes, it is possible. It can be a bit complicated, though — i’ll leave you to work out the maths yourself. Try juggling a bit with the number 31.