GESP Level 2 C++ Programming (53C++): Digit Sum – Mistakes Due to Habits

For the GESP Level 2 exam: C++ 202412 Level 2 Digit SumThis problem is relatively simple, but there is a major difficulty:Many candidates can solve it, the debugging is correct, and the test cases pass, but after submission, it is incorrect and does not receive full marks. They repeatedly modify their code but cannot find the solution.Why is that?Look at the problem:GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to Habits

Solution Approach:

1. Loop through the input, break down each digit, sum them up, and find the maximum value. The result is positive, perfect.

#include <bits/stdc++.h>using namespace std;int main(){    int n;    int result, maxR = 0;    cin >> n;    for (int i = 0; i < n; i++)    {        result = 0;        int a;        cin >> a;        while (a)        {            result += a % 10;            a = a / 10;        }        maxR = max(maxR, result);    }    cout << maxR;}

GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to Habits

After submission:

GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to HabitsGESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to HabitsWhere did it go wrong?GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to HabitsWhy does it seem correct in all tests?Many candidates just give up like this…Actually, it’s quite simple; the mistake lies in a very small detail. Look at the last line of the problem statement.

GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to Habits

Let’s take a look at the data types:

Unsigned storage Maximum value of int type

  • Fixed at 32 bits (4 bytes)
  • Corresponding maximum value <span>UINT_MAX = 2^32 - 1 = 4294967295</span> (approximately 4×10⁹).
Unsigned long long

  • 64 bits (8 bytes).
  • Maximum value<span>ULLONG_MAX = 2^64 - 1 = 18446744073709551615</span> (approximately 1.8×10¹⁹).
Unsigned long

  • 32 bits (4 bytes).
  • Maximum value<span>ULONG_MAX = 2^32 - 1 = 4294967295</span> (approximately 4×10⁹).

Now you know where the mistake is! You cannot habitually use int; you must pay attention to the data range.

#include <bits/stdc++.h>using namespace std;int main(){    int n;    int result, maxR = 0;    cin >> n;    for (int i = 0; i < n; i++)    {        result = 0;        long long a; // This is very important        cin >> a;        while (a)        {            result += a % 10;            a = a / 10;        }        maxR = max(maxR, result);    }    cout << maxR;}

GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to HabitsThis is perfect!Read the problem carefully, pay attention to the data range…Have you learned it?GESP Level 2 C++ Programming (53C++): Digit Sum - Mistakes Due to Habits

Leave a Comment