Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

c# - Unexpected u0000 insted of '0' when concatenate char arrays

I've got unexpected u0000 at leetcode:

enter image description here

Same code works fine locally in linqpad:

public string AddBinary(string a, string b)
{
    var result = a.Length > b.Length
        ? new char[a.Length]
        : new char[b.Length];

    result.Dump();

    bool carry = false;
    
    var iA = a.Length - 1;
    var iB = b.Length - 1;

    while (!(iA < 0 && iB < 0))
    {
        var bA = iA < 0 ? false : a[iA] == '1';
        var bB = iB < 0 ? false : b[iB] == '1';

        //char cA = iA < 0 ? '-' : a[iA];
        //char cB = iB < 0 ? '-' : b[iB];
        //$"string a. i = {iA} cA = '{cA}' {bA}".Dump();
        //$"string b. i = {iB} cB = '{cB}' {bB}".Dump();
        
        bool bCurrent = bA ^ bB ^ carry;

        int position = iA < 0 ? iB : iA;
        
        result[position] = bCurrent ? '1' : '0';
        
        carry = carry 
                ? !(!bA && !bB)
                : bA && bB;
        
        iA--;
        iB--;
    }
    
    result.Dump();

    if(!carry)
        return new string(result);
        
    var newResult = new char[result.Length + 1];
    newResult[0] = '1';
    for (int i = 0; i < result.Length; i++)
    {
        newResult[i+1] = result[i];
        result[i].Dump();
    }
    result.Dump();
    var ab = new string(newResult);
    DisplayString(ab);
    ab.Dump();
    return ab;

    //var one = new char[] { '1' };
    //result.Dump();
    //var newResult = one.Concat(result);
    //newResult.Dump();
    //var r = new string(newResult.ToArray());
    //r.Dump();
    //return r;
}

(see DisplayString definition at John's Skeet page)

Here is some debug info during this test case:

enter image description here

Second version has same error:

enter image description here

So, there's no place where u0000 came from. Is it an bug? Or maybe i miss something?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is in the calculation of the position:

int position = iA >= iB ? iA : iB;

You need to use the maximum position.

As you wrote, with 1 and 111, in the first loop you have: iA == 0, iB == 2, position == 0 instead of position == 2 (so you are writing the first element instead of the last)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...