Reputation: 4663
This is what I have been working on:
Giving input as 2 positive integers (at most, 100 digits).
Compare the two integers.
Note: The 2 integers can contain leading zeros. (that means you have to remove zeros first)
Because 100 digits is too long, I use a string
datatype.
But in my program below, it just returns '='
I debugged it and figured out that the for
loop isn't working.
My code:
#include <iostream>
#include <string>
using namespace std; // I know this is bad but it's just a small program
char compareBigInterger(string str1,string str2)
{
while (str1[0] != 0) str1.erase(0, 1);
while (str2[0] != 0) str2.erase(0, 1);
char answerHold {'='};
if (str1.size() > str2.size())
{
answerHold = '>';
}
else if (str1.size() < str2.size())
{
answerHold = '<';
}
else
{
for (int i = 0; i < str1.size(); i++)
{
if (int(str1[i] - 48) < int(str2[i] - 48)) // 48 = '1' - 1
{
answerHold = '<';
break;
}
else if (int(str1[i] - 48) > int(str2[i] - 48))
{
answerHold = '>';
break;
}
}
}
return answerHold;
}
int main()
{
string str1;
string str2;
cin >> str1 >> str2;
cout << char{compareBigInterger(str1, str2)};
}
Upvotes: 1
Views: 313
Reputation: 75062
The lines
while (str1[0] != 0) str1.erase(0, 1);
while (str2[0] != 0) str2.erase(0, 1);
will erase all characters in the strings because the value 0
is used as the end mark of strings.
To compare with character zero, you should use character literal '0'
(character surrounded with ''
).
Also the loop should be "loop while the character is zero" to remove zeros.
while (str1[0] == '0') str1.erase(0, 1);
while (str2[0] == '0') str2.erase(0, 1);
Upvotes: 5