简体   繁体   中英

Splitting a number in half but fixing when second half starts with 0

I have a large number that I want to split in half. For this example, let's use: 5639445604728832

When it is split in half it comes out like this:

56394456
04728832

Obviously, the second number isn't a number anymore.

I have the following code, but I am trying to make it so it will add the 0 's to the end of the first number until the second number is officially a real number. Could anyone help me solve this?

function my_number_split($number)
{
    $half = (int) ( (strlen($number) / 2) ); // cast to int incase str length is odd
    $left = substr($number, 0, $half);
    $right = substr($number, $half);

    echo $left."<br />".$right;
}

Rewriting your function like this would do the trick.

function my_number_split($number)
{
    $half = ceil( (strlen($number) / 2) ); 
    while (0 == substr($number, $half, 1) && $half <= strlen($number) ) $half++;
    $left = substr($number, 0, $half);
    $right = substr($number, $half);

    echo $left."<br />".$right;
}

Simple loop should do it.
Something like this -

function my_number_split($number)
{
    /* Logic to traverse ahead till a 0 is not found. */
    $str_len = strlen($number);
    $half_index = $str_len/2;
    while($half_index < $str_len){
        if($number[$half_index] != "0"){
            break;
        }
        $half_index++;
    }
    //Slicing string.
    $left = substr($number, 0, $half_index);
    $right = substr($number, $half_index);
    echo $left."<br />".$right;
}
my_number_split("5639445604728832");

/*
OUTPUT -
563944560
4728832
*/

It's probably an inefficient way, but for the challenge:

if (preg_match('~\A(?<n1>.?(?:.(?=.*(.(?(2)\2)\z)))+0*)(?<n2>.+)~', $number, $m))
    echo $m['n1'] . "\n" . $m['n2'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM