Skip to content

Instantly share code, notes, and snippets.

@dangngocduc
Created November 18, 2022 04:05
Show Gist options
  • Select an option

  • Save dangngocduc/438a73b1a95076acb8a2362fd6ed225d to your computer and use it in GitHub Desktop.

Select an option

Save dangngocduc/438a73b1a95076acb8a2362fd6ed225d to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'dart:io';
void main() {
String a = stdin.readLineSync();
String b = stdin.readLineSync();
print (multiplication(a.trim(), b.trim()));
}
String multiplication (String a, String b) {
if (a.length == 0 || b.length == 0) {
return '0';
}
int sumLength = a.length + b.length;
List<int> result = List.filled(a.length + b.length, 0);
int index1 = 0;
for(int i = (a.length - 1); i >= 0; i--) {
int index2 = 0;
int surplus = 0;
for(int j = (b.length - 1); j >= 0; j--) {
int sum = int.parse(a[i]) * int.parse(b[j]) + surplus + result[sumLength - (index1 + index2) - 1];
result[sumLength - (index1 + index2) - 1] = sum % 10;
surplus = (sum / 10).toInt();
index2 ++;
}
if (surplus != 0) {
result[sumLength - (index1 + index2) - 1] = surplus;
}
index1 ++;
}
if (result.every((e) => e == 0)) {
return '0';
}
String s = '';
for (var e in result) {
if (!(result.indexOf(e) == 0 && e == 0))
s = s + e.toString();
}
return s;
}
import "dart:io";
void main() {
String num1 = stdin.readLineSync();
String tempNum1 = num1;
String num2 = stdin.readLineSync();
String tempNum2 = num2;
// Check negative
if (num1[0] == "-" && num2[0] != "-") {
num1 = num1.substring(1);
} else if (num1[0] != "-" && num2[0] == "-") {
num2 = num2.substring(1);
} else if (num1[0] == "-" && num2[0] == "-") {
num1 = num1.substring(1);
num2 = num2.substring(1);
}
String s1 = num1;
String s2 = num2;
s1 = num1.split('').reversed.join();
s2 = num2.split('').reversed.join();
int lengthList = s1.length + s2.length;
List<int> m = [];
for (int i = 0; i < lengthList; i++) {
m.addAll([0]);
}
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
m[i + j] =
m[i + j] + (s1[i].codeUnitAt(0) - 48) * (s2[j].codeUnitAt(0) - 48);
}
}
// print(m);
String product = "";
for (int i = 0; i < m.length; i++) {
int digit = m[i] % 10;
int carry = m[i] ~/ 10;
if (i + 1 < m.length) {
m[i + 1] = m[i + 1] + carry;
}
product = digit.toString() + product;
}
while (product.length > 1 && product[0] == "0") {
product = product.substring(1);
}
if (tempNum1[0] == '-' && tempNum2[0] != '-') {
product = "-" + product;
} else if (tempNum1[0] != '-' && tempNum2[0] == '-') {
product = "-" + product;
}
print(product);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment