moray95
moray95

Reputation: 977

Ambiguous conversion - C++

I'm trying to code a function using C++ and Xcode as compiler that will test if a is palindrome or not. The code works well when the argument is a "C++ born" type (such as int, long, double etc.) but I want to use the function for larger values. So I used an argument of type BigInteger. But the compiler gives an error on the line

 BigInteger q = x - floor(x.toLong()/10)*10

saying that Conversion from 'double' to 'const BigInteger' is ambiguous. Here is the whole code :

#include <iostream>
#include "BigInteger.hh"

using namespace std;
bool isPalindrom(BigInteger x){
long ch = ceil(log10(x.toUnsignedLong())), n[ch];
//    cout << floor(log10(x)) + 1 << endl;
for (int i = 0; i <= ch; i++){
    BigInteger q = x - floor(x.toLong()/10)*10;
    n[i] = q.toInt();
    //        cout << n[i] << endl;
    x /= 10;
}

for (long i = 0; i <= ceil(ch); i++){
    if (n[i] != n[ch - i]){
        return false;
    }
}
return true;
}

How can I solve this problem?

Upvotes: 0

Views: 1355

Answers (2)

molbdnilo
molbdnilo

Reputation: 66451

There's little point in using BigInteger if you're going to convert to longs all the time.

You can write that thing using only BigInteger operations, in exactly the same way as you would with primitive integers:

bool isPalindrome(BigInteger x){
   std::vector<int> digits;
   while (x > 0)
   {
      digits.push_back((x % 10).toInt());
      x /= 10;
   }

   size_t sz = digits.size();
   for (size_t i = 0; i < sz; i++){
      if (digits[i] != digits[sz - i - 1]){
         return false;
      }
   }
   return true;
}

Upvotes: 1

perhaps

  BigInteger q (static_cast<long>(x - floor(x.toLong()/10)*10));

might make the compiler happier. Look inside BigInteger.hh for the public constructors. Notice that floor gives a double, hence the substraction gives also a double, and BigInteger has no constructor for that.

Upvotes: 0

Related Questions