如何计算两个整数的相似性? [英] How do I calculate similarity of two integers?
本文介绍了如何计算两个整数的相似性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
其实这是相当难来形容:结果
我想要实现它通过在同一位置的图对比图(因为我做我在基于10系统计算,这是相当相同的权力的算法的的两个给定的整数/数字(具有相同)长度)十位。它应该返回平等的等级如下:
- 4491和1020 = 0
- 4491及4123 = 1
- 4491和4400 = 2
- 4491及4493 = 3
- 4491及4491 = 4
- 4491及4091 = 1
我不希望我的计算基础上做一个字符串比较,因为我会在某种程度上这样做更大的情景:)
解决方案
公共静态INT比较(INT I1,I2 INT)
{
INT结果= 0;
,而(I1 = 0&安培;!&安培;!I2 = 0)
{
VAR D1 = I1%10;
VAR D2 = I2%10;
的i1 / = 10;
I2 / = 10;
如果(D1 D2 = =)
{
++的结果;
}
,否则
{
结果为0;
}
}
如果(I1!= 0 || I2!= 0)
{
抛出新的ArgumentException(整数必须相同的长度。) ;
}
返回结果;
}
请注意:它不处理负整数
更新:固定的问题,更新后
Actually it's quite hard to describe:
I want to implement an algorithm which compares figure by figure of the same position (as I do my calculations in a 10-based system it's rather the same "power of ten") of two given integers/number (with the same "length"). It should return the grade of equality as following:
- 4491 and 1020 = 0
- 4491 and 4123 = 1
- 4491 and 4400 = 2
- 4491 and 4493 = 3
- 4491 and 4491 = 4
- 4491 and 4091 = 1
I do not want to do my calculations based on a string-comparison, as I'll doing this in a way bigger scenario :)
解决方案
public static int Compare(int i1, int i2)
{
int result = 0;
while(i1 != 0 && i2 != 0)
{
var d1 = i1 % 10;
var d2 = i2 % 10;
i1 /= 10;
i2 /= 10;
if(d1 == d2)
{
++result;
}
else
{
result = 0;
}
}
if(i1 != 0 || i2 != 0)
{
throw new ArgumentException("Integers must be of same length.");
}
return result;
}
Note: it does not handle negative integers
Update: fixed after question update
这篇关于如何计算两个整数的相似性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文