Row multiplication

I am trying to multiply two lines, but I am getting the wrong answer. Any help would be appreciated:

public class stringmultiplication {
    public static void main(String[] args) {
        String s1 = "10";
        String s2 = "20";
        int num = 0;
        for(int i = (s1.toCharArray().length); i > 0; i--)
            for(int j = (s2.toCharArray().length); j > 0; j--)
                num = (num * 10) + ((s1.toCharArray()[i - 1] - '0') * (s2.toCharArray()[j - 1] - '0'));
        System.out.println(num);
    }
}
+3
source share
4 answers
public static void main(String[] args) {
        String number1 = "108";
        String number2 = "84";

        char[] n1 = number1.toCharArray();
        char[] n2 = number2.toCharArray();

        int result = 0;

        for (int i = 0; i < n1.length; i++) {
            for (int j = 0; j < n2.length; j++) {
                result += (n1[i] - '0') * (n2[j] - '0')
                        * (int) Math.pow(10, n1.length + n2.length - (i + j + 2));
            }
        }
        System.out.println(result);
    }

This should be the correct implementation without using integers.

+3
source

You multiply digits by digits and you do not correctly control the values โ€‹โ€‹of 10.

First you need to parse the strings into integers. You are on the right track. You can simplify loop indices, and you only need to call toCharArrayonce. For instance:.

After parsing, you can multiply integers.

EDIT: if this is not allowed, you need to implement an algorithm like this one , which is a bit more complicated.

(n + 1) x (m + n) ( ), m n - . 0, . . , , .

. :

int[][] intermediates = new int[3][4];

.

+2

- , , , .

public class T{  
    public static void main(String[] args) {     

        char[] num1 = "127".toCharArray();     
        char[] num2 = "32".toCharArray();

        int[] intermediate = new int[num1.length];

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

                for(int j = 0 ; j < num2.length ; j++ ) { 


                  int d1 = num1[num1.length - i - 1]-'0';
                  int d2 = num2[num2.length - j - 1]-'0';


                  intermediate[i] += d1 * d2 * (int) Math.pow(10,j);

                  System.out.printf("  %d X %d = %d\n", d1, d2, intermediate[i]);

                }     

             intermediate[i] *= (int) Math.pow(10,i);

             System.out.println(" intermediate : " + intermediate[i]);
        }     


        int sum = 0;

        for(int i : intermediate) {
            sum += i;
        }

        System.out.println("Sum is = " + sum); 
    }
} 
+1

, pow, . . char [], .

public static int multiply (char A[], char B[]){
		int totalSum = 0, sum = 0;
		for (int i = 0; i < A.length; i++){
			sum = 0;

			for (int j = 0; j < B.length; j++){
				sum *= 10;
				sum += (A[i] - '0') * (B[j] - '0');
				
			}
			totalSum *=10;
			totalSum += sum;
		}

		return totalSum;
	}
Hide result
0

Source: https://habr.com/ru/post/1780340/


All Articles