Question about directly usage of s.length() and int size = s.length() ?

  • 0

    I have a code with 4-based integer that got MLE if I directly use

    for(int i = 0; i < s.length() -10; i++)

    but if I define an integer variable

    int size = s.length();

    and use this variable in for loop, it is accepted. why this happened?

  • 0

    When you call the function s.length(), the length of the string is calculated every time. If you store it in a variable, the method can just refer to it.

  • 0

    s.length() returns an unsigned integer, and 10 is an signed integer. When doing s.length() - 10, 10 is cast to an unsigned integer. If the length of s is less than 10, this calculation causes underflow, and the result is an very large integer.

    But if you use int size = s.length(), the cast has done in this assignment statement, and you won't get error in the loop.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.