我正在尝试比较长字符串数字。数字长度在1到50之间。比较字符串的长度效果很好,但如果长度相等则有点困难。我决定将字符串变成数组,并比较值,直到它们不同为止。我认为这是格式错误,但我不确定。
function compareIntegers(a, b) {
//coding and coding..
var aSplit = a.split("")
var bSplit = b.split("")
if (a.length > b.length){
return "greater";
}
if (b.length > a.length){
return 'less';
}
if (a.length == b.length){
for (i=0; aSplit.length; i++){
if (bSplit.indexOf(aSplit[i] ===-1) {
if (aSplit[i] > bSplit[i]){
return 'greater';
}
if (aSplit[i] < bSplit[i]){
return 'less';
}
else return 'equal';
}
}
}
}
describe("Basic Tests", function(){
it("It should works for basic tests.", function(){
Test.assertEquals(compareIntegers("12","13"),"less")
Test.assertEquals(compareIntegers("875","799"),"greater")
Test.assertEquals(compareIntegers("1000","1000"),"equal")
Test.assertEquals(compareIntegers("999","1000"),"less")
Test.assertEquals(compareIntegers("123","122"),"greater")
Test.assertEquals(compareIntegers(
"1000000000000000000000000000000000",
"1000000000000000000000000000000001"),
"less"
)
Test.assertEquals(compareIntegers(
"1000000000000000000000000000000002",
"1000000000000000000000000000000001"),
"greater"
)
Test.assertEquals(compareIntegers(
"10000000000000000000000000000000000",
"1000000000000000000000000000000001"),
"greater"
)
})})
答案 0 :(得分:1)
没有理由将字符串拆分为数组,您可以使用索引属性或.charAt()
轻松访问单个字符。并且没有理由自己完成这种逐个字符的比较(并且会犯bSplit.indexOf(aSplit[i])
这样的错误),这只是比较两个字符串的默认行为。所以我写了
function compareIntegerStrings(a, b) {
a = a.replace(/^0*/, ""); // strip leading zeroes
b = b.replace(/^0*/, "");
if (a.length > b.length){
return 1;
} else if (b.length > a.length){
return -1;
} else { // a.length == b.length
if (a > b) {
return 1;
} else if (b > a) {
return -1;
}
}
return 0;
}
function comparisonToString(c) {
return ['less', 'equal', 'greater'][Math.sign(c)];
}
您还可以将compareIntegerStrings
中的比较金字塔缩短为
return Math.sign(a.length - b.length) || +(a>b) || -(a<b);