Multiply Strings

 

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

思路: 用加法模拟乘法运算

注意事项:输出结果高位为0要舍去,如果只有一个0,要保留

JAVA代码:

  1. public String multiply(String num1, String num2) {
  2. ArrayList<Integer> res = new ArrayList<Integer>();
  3. int nlen1 = num1.length();
  4. int nlen2 = num2.length();
  5. for(int i=0;i<=nlen1+nlen2-2;i++) {
  6. res.add(0);
  7. }
  8. for(int i=0;i<nlen1;i++) {
  9. for(int j=0;j<nlen2;j++) {
  10. res.set(i+j,res.get(i+j) + (num1.charAt(i) - '0') * (num2.charAt(j) - '0')); // 要用set方法设置
  11. }
  12. }
  13. int cnt=0;
  14. StringBuffer result = new StringBuffer();
  15. for(int i=res.size()-1;i>=0 || cnt!=0;i--) {
  16. int cur = 0;
  17. if(i>=0) {
  18. res.set(i,res.get(i) + cnt);
  19. if(res.get(i) >= 10) {  // >=10
  20. cnt = res.get(i)/10;
  21. res.set(i,res.get(i)%10);
  22. } else {
  23. cnt = 0;  // 要控制好进位
  24. }
  25. cur = res.get(i);
  26. } else {
  27. cur = cnt;
  28. if(cur>=10) {
  29. cnt = cur/10;
  30. cur = cur%10;
  31. } else {
  32. cnt = 0;
  33. }
  34. }
  35. result.append(cur);
  36. }
  37. StringBuffer result2 = result.reverse();
  38. int i=0;  //声明的控制
  39. for(i=0;i<result2.length();i++) {  //对结果的处理,高位0的消除
  40. if(result2.charAt(i)!='0') break; 
  41. }
  42. if(i==result2.length()) return "0";  //保留一个
  43. return result2.substring(i).toString();
  44. }
posted @ 2014-07-09 15:09  purejade  阅读(81)  评论(0)    收藏  举报