Home > database >  difference between size_t and int in a "Plus One" problem algorithm
difference between size_t and int in a "Plus One" problem algorithm

Time:10-16

vector<int> plusOne(vector<int>& digits) {
    int n = digits.size();
    for (int i = n - 1; i >= 0; i--){
        if (digits[i] < 9){
            digits[i]  ;
            return digits;
        }
        else{
            digits[i] = 0;
        }
    }
    digits.insert(digits.begin(), 1);
    return digits;
    
}

it's a Plus One problem. "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits."

why this particular solution does not work with size_t instead of int in for loop?

CodePudding user response:

Because size_t is an unsigned type. If i is a size_t, then

i >= 0

is always true because, by definition, an unsigned value is never less than 0.

To make it work with a size_t type it will be necessary to adjust the overall logic, in order to accommodate it. Something like:

for (size_t i = digits.size(); i-- > 0; ){

CodePudding user response:

The expression i>=0 will always evaluate to true if i is of type size_t because size_t is an unsigned type.

  • Related