首页 > 代码库 > 仿网易一元夺宝算法,宽长度数据计算,字符串实现
仿网易一元夺宝算法,宽长度数据计算,字符串实现
/**
* @company
* @version 1.0
* @author fangjianming
* @email fangjianming_gis@163.com
* @date 2014年12月10日
*/
public class Cal {
public static void main(String[] args) {
String value = "http://www.mamicode.com/581999974";
String value2 = "46658";
long bet = 100;
String value3 = "10000001";
// 计算求和
int []eleven = addString(value,value2);
// 计算求余数
long result = divideInt(eleven,bet);
// 计算结果
int []intValue = http://www.mamicode.com/addString(value3,String.valueOf(result));
// Int[]转Char[]
char [] charValue = http://www.mamicode.com/transIntArrayToCharArray(intValue);
System.out.print(charValue);
}
// Int[]转Char[]
private static char[] transIntArrayToCharArray(int[] intValue) {
if(intValue =http://www.mamicode.com/= null || intValue.length ==0 )
throw new NullPointerException("eleven must bot be null");
char[] charValue = http://www.mamicode.com/new char[intValue.length];
int i = 0;
for(int value:intValue)
{
charValue[i++] = (char) (value +48);
}
return charValue;
}
// 计算求余数
private static long divideInt(int[] eleven, long divide) {
if(eleven == null || eleven.length ==0 )
throw new NullPointerException("eleven must bot be null");
if(divide == 0)
throw new NullPointerException("divide must bot be zero");
long result = 0;
int len = eleven.length;
for(int i = 0;i<len ;i++)
{
int tmp = eleven[i];
result = tmp+10*result;
if(result >= divide)
{
result %= divide;
}
}
return result;
}
// 计算求和
public static int [] addString(String value1,String value2)
{
if(value1 == null || value2 == null || value1 =="" ||value2 == "")
throw new NullPointerException("value1 and value2 must bot be null");
String max = (value1.length() > value2.length())?value1:value2;
String min = (value1.length() <= value2.length())?value1:value2;
int len = max.length();
int len2 = min.length();
int ten = 0;
int ge = 0;
int []eleven = new int[len];
for (int i = max.length()-1,j = min.length()-1 ; i >= 0 ;i--,j--)
{
int a1 = 0;
int a2 = 0;
a1 = max.charAt(i)-48;
if(j>=0)
a2 = min.charAt(i-(max.length()-min.length()))-48;
ge = (a1+a2+ten) % 10;
ten = (a1+a2) / 10;
eleven[i] = ge;
}
if(ten >0)
{
int []eleven2 = new int[len+1];
eleven2[0] = ten;
for(int j = 0;j <len ;j++)
{
eleven2[j+1] = eleven[j];
}
return eleven2;
}
return eleven;
}
}
仿网易一元夺宝算法,宽长度数据计算,字符串实现