比较两个字符串作为数值 [英] Compare two string as numeric value

查看:44
本文介绍了比较两个字符串作为数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何比较 C++ 中表示数字的两个字符串?我想转换为long long 类型的数字,但问题是字符串表示的数值可能超过long long MAX 限制.保证字符串代表一个数值.

How should I compare two string representing numbers in C++? I thought of converting to number of long long type but the problem is the numerical value represented by string can exceed the long long MAX limit. It is guaranteed that the string represents a numerical value.

Java 中有一个类似的问题比较两个数字字符串值.但这利用了我们在 C++ 中没有的 BigInteger 库.

There is a similar question in Java compare two numeric String values. but that makes use of the BigInteger Library that we don't have in C++.

推荐答案

逐个比较:

a = "3254353245423345432423133423421"
b = "3254353245423345432443133423421"

for(int i = 0; i < a.length(); ++i):
    if ((a[i] - '0') < (b[i] - '0'))
    { 
        std::cout << "b is larger!" 
    }

如果你想知道 b 是否大于 a,或者它们是否相等,我相信你可以从这里获取它.或者,如果它们的长度不同,则较大者获胜!(检查开头是否有零,即 "000443342")不要忘记考虑负数.

I'm sure you can take it from here if you want to find out whether b is larger than a, or if they are equal. Alternatively, if they are different lengths, the larger one wins! (Check for zeros at the beginning, i.e. "000443342") Don't forget to consider negative numbers.

这篇关于比较两个字符串作为数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆