-2

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

class Solution {
public:
    vector<int> addToArrayForm(vector<int>& A, int K) {
     int i=A.size()-1;
     vector<int> result={};
     long long int no=0;
      for(int x:A)
      {
          no=no+x*pow(10,i);
          i--;
      }
      no=no+K;
      if(no==0)
          return {0};
      while(no>0)
      {
          long long int r=no%10;
          result.push_back(r);
          no=no/10;
      }
     reverse(result.begin(),result.end());
     return result;
     
    }
};

I am getting this error with long long.

Line 9: Char 14: runtime error: 1e+19 is outside the range of representable values of type 'long long' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:18:14

Himanshu Ranjan
  • 282
  • 1
  • 7
  • 22
  • 1
    `A` can be of arbitrary size. Your compiler is telling you that this function will generate overflows if A is ever larger than 19 elements. – Botje Oct 01 '20 at 08:09
  • 1
    Also note that [`pow` is a dangerous way of computing integer powers](/questions/33187956/c-pow-unusual-type-conversion) – Botje Oct 01 '20 at 08:10
  • Yea I will work on an optimized solution now – Himanshu Ranjan Oct 01 '20 at 08:13

2 Answers2

2

Provided that long long is implemented by a signed 64-bit integer, 1e19 is indeed out of the positive range of that type. The maximum representable value of that type would be 9223372036854775807.

As to whether 1e19 is a possible value, it is because it depends on the size of the vector A that you pass as input. You may want to limit your algorithm to only accept A of up to a certain size by adding a check against std::numeric_limits<long long>::digits10.

Andrey Semashev
  • 10,046
  • 1
  • 17
  • 27
0

maybe initialise std::vector<long long int> result will solve your problem. Because you defined it as an integer, but you pusing back long long variable.

or you can use static_cast<type> to convert types temprorary for ongoing alegorithm (cppref: static_cast)

disclaimer: I answered, because I can't comment (I don't have 50 rep)