`
blueyanghualong
  • 浏览: 221835 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

计算两个大数相乘的Java算法实现(ZZ)

阅读更多


/**

 * 关于两个大的数值相乘 

 * 思路解决:

 *   将Str类型转换成一个对象存取 包括 长度以及数组存取Str的值

 *   然后将两个数组相乘 存放在第三个数值中 然后将大于9的向前近卫

 *   最后打印出这个相乘的

 *   数组

 * 

 * @author meachalyang

 * @since 2011-01-07

 *

 */

public class test {


public static void main(String[] args) {

//创建一个定义输入的编辑器

/**

* 创建一个编辑器 用于输入字符

*/

System.out.println("Input two large integers:..");

BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));

String[] strArry =null;

try {

       strArry= buffer.readLine().split("*");

} catch (IOException e) {

// TODO Auto-generated catch bloc

e.printStackTrace();

}

/**

* 定义两个字符串变量 获取输入的值

* 这段代码 请不要严格 计较 哈哈

*/

String strMulA=strArry[0];

String strMulB=strArry[1];

/**

* 将输入的字符串变量转换到与字符串本身等长的数组中

*/

       //写一个存储字符串并转换为数组的方法

int[]intMulA=strToArray(strMulA);

int[]intMulB=strToArray(strMulB);

//然后将这个两个数组相乘 并保存在第三个数组中

   /* 定义第三个数组*/

/**

* 打印 frist num and second num len logs 

*/

System.out.println("frist num len:"+intMulA.length);

System.out.println("second num len:"+intMulB.length);

//定义一个mul数组用于存取结果

int[]intMulResult=new int[intMulA.length+intMulB.length-1];

int num=0;

/**

* 根据两个转型后的数值 进行乘法运算

*/

getMulValue(intMulA, intMulB, intMulResult);

 

System.out.println("get mul len:"+intMulResult.length);

System.out.print("get mul :");

for (int i = 0; i < intMulResult.length; i++) {

System.out.print(intMulResult[i]);

}

 

}

   /**

    * 此方法封装了 得到获取乘集的算法

    * 根据 frist num &second num 逐步相乘的原理 例如

    * 222*321 可以拆分为  2*100*3*100+2*100*2*10+200*1

    *                  + 2*10*3*100+2*10*20+20*1

    *                  + 2*300+2*20+20*1

    *  正好对应数组的每个索引位置

    *  

    *  然后将每个索引位置大于9的向前进一位 并保留余数                              

    * @param mulNumA 乘数1

    * @param mulNumB 乘数2

    * @param mulResult result

    */

private static void getMulValue(int[] mulNumA, int[] mulNumB, int[] mulResult) {

//拆分乘积算法

for (int i = 0; i < mulNumA.length; i++) {//222

//20   1 2*3+ 2*0+0*3+0*0  

for (int j = 0; j < mulNumB.length; j++) {//333

mulResult[i+j]+=mulNumB[j]*mulNumA[i];

}

}

//200*321  71262

//222*1+222*20+222*300

//666[2]+6660[1]+66600[0]

// 200*300+200*20+200*1  64200

// 10*300+10*20+10*1   6420

// 2*300+2*20+2*1         642

//剔除intStr3数组中个位置上的大于9的数

   for (int i = mulResult.length-1; i >0; i--) {

if(mulResult[i]>9){

mulResult[i-1]+=mulResult[i]/10;

mulResult[i]=mulResult[i] % 10;

}

}

}

/**

* 将字符串每个字符的值 定义并存储在数组中

* @param str  传入的字符串

* @return 

*/

@SuppressWarnings("null")

public static  int[] strToArray(String str)

{

int [] strToArray=new int[str.length()];

//写一个将str转为数组的方法 逐步遍历每个字符

int len=str.length();

if(str!=null&&!"".equals(str))

{

for (int i = 0; i < str.length(); i++) {

int num=str.charAt(i)-'0';

strToArray[i]=num;//charAt方法返回ASII吗 所以这里要减去0对应的ASII

}

}

return strToArray;

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics