您的位置:首页 > 其它

一个简单实现的字符串数字乘法。

2013-12-19 16:26 323 查看
public class multiply {

public static void main(String[] args) {

String result = "1";

//阶乘

for(int i = 1; i <= 1493; i++)

{

result = multiString(result,String.valueOf(i));

}

System.out.println(result);

}

/**

* 字符串乘法

*/

public static String multiString(String m1, String m2)

{

String result = null;

//数字1,2长度

int lm1 = m1.length();

int lm2 = m2.length();

//结果最大长度

int lres = lm1 + lm2 + 1;

//结果数组

int[] intres = new int[lres];

int count = 0;

for(int i1 = lm1 - 1; i1 >=0; i1--)

{

for(int i2 = lm2 - 1; i2 >=0; i2--)

{

int t = (int)(m1.charAt(i1) - 48) * (int)(m2.charAt(i2) - 48);

//获取到当前要加的位置。

count = lm2 - 1 - i2 + (lm1 - 1 - i1);

//t必然为2位数。

int t0 = t % 10;

int t1 = t / 10;

int jinwei = 0;

//将新的结果加到已生成的结果上去

intres[count] = t0 + intres[count];

jinwei = intres[count] / 10;

intres[count] = intres[count] % 10;

count++;

intres[count] = t1 + intres[count] + jinwei;

//整理进位

while(intres[count] / 10 > 0)

{

jinwei = intres[count] / 10;

intres[count] = intres[count] % 10;

count++;

intres[count] = intres[count] + jinwei;

}

}

}

StringBuffer sbres = new StringBuffer();

//是否去除0的标识

int flag = 1;

for(int i = lres - 1; i >= 0; i--)

{

// 去除开头的0;

if(intres[i] == 0 && flag == 1)

{

continue;

}

//不再去除之后的0

flag = 0;

//将数组转化为String

sbres.append(intres[i]);

}

result = sbres.toString();

return result;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: