踩坑:字符串、数字:比较大小

一、两个字符串比较大小

let a = '2'
let b = '11'
console.log(a > b) // true
// 说明:先比较首位2、1,true返回true
// 专业解释:ASCII码比较,依次取每个字符,字符转为ASCII码进行比较,ASCII码先大的即为大,这时候就不会在比较后面了

a = '112'
b = '12'
console.log(a > b) // false
// 先比较首位1、1,相等则比较第二位1、2,false则返回false

a = '2abc'
b = '29'
console.log(a > b) // true
// ASCII码比较,a的ASCII码值为97,97大于9,故为true

二、数值、字符串比较大小

let c = 2
let d = 11
console.log(c > d) // false
// 直接正常数学比较大小

c = 2
d = '11'
console.log(c > d) // false
// 先把'11'隐式转换为Number类型11,再进行数学比较

c = '2'
d = 11
console.log(c > d) // false
// 先把'2'隐式转换为Number类型2,再进行数学比较

c = '2abc'
d = 11
console.log(c > d) // false
// 不规则字符串数字比较,先把'2abc'隐式转换为NaN,再与数值11比较,数值比较会一直为false

《字符串、数字:比较大小》我不信我下次还会踩坑!!!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
如果两个超长数字字符串均超过20位,则我们需要使用高精度计算的方法来比较它们的大小。 一种比较简单的方法是将两个字符串转换为两个高精度整数,然后进行比较。以下是一种实现方式: 1. 定义一个高精度整数类,可以参考以下代码: ```c++ #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; class BigInt { public: BigInt() {} BigInt(string s) {*this = s;} BigInt operator = (string s) { num.clear(); for (int i = s.size() - 1; i >= 0; i -= 9) { int j = max(0, i - 8); num.push_back(stoll(s.substr(j, i - j + 1))); } return *this; } BigInt operator + (BigInt &b) { BigInt c; c.num.clear(); for (int i = 0, g = 0; ; i++) { if (g == 0 && i >= num.size() && i >= b.num.size()) break; long long x = g; if (i < num.size()) x += num[i]; if (i < b.num.size()) x += b.num[i]; c.num.push_back(x % 1000000000); g = x / 1000000000; } return c; } bool operator < (const BigInt &b) const { if (num.size() != b.num.size()) return num.size() < b.num.size(); for (int i = num.size() - 1; i >= 0; i--) if (num[i] != b.num[i]) return num[i] < b.num[i]; return false; } bool operator == (const BigInt &b) const { if (num.size() != b.num.size()) return false; for (int i = 0; i < num.size(); i++) if (num[i] != b.num[i]) return false; return true; } private: vector<long long> num; }; ``` 2. 然后,我们可以将两个字符串转换为两个 BigInt 对象,并使用 “<” 和 “==” 运算符来比较它们的大小。以下是一段示例代码: ```c++ #include <iostream> #include <string> using namespace std; class BigInt { // 定义 BigInt 类 // ... }; int main() { string s1 = "12345678901234567890"; string s2 = "98765432109876543210"; BigInt n1(s1); BigInt n2(s2); if (n1 < n2) { cout << s1 << " < " << s2 << endl; } else if (n1 == n2) { cout << s1 << " = " << s2 << endl; } else { cout << s1 << " > " << s2 << endl; } return 0; } ``` 输出结果为: ``` 12345678901234567890 < 98765432109876543210 ``` 这样,我们就可以比较两个超长数字字符串大小了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值