0

I want to solve leetcode 172nd question using dart. Take the factorial of a given number and find how many zeros there are at the end.

I done until now

void main() {
  print(factorial(5));

}

factorial(int input) {
  int factorial = 1;
  var answer = 0;
  for (int i = 1; i <= input; i++) {
    factorial *= i;
  }

  while (factorial > 10 && factorial.toString().split('').last == "0") {
    factorial = (factorial / 10)

    answer++;
  }

  return answer;
}

but when i divide factorial by 10 it not allowed. and if assing at the begining like

double factorial=1;

this time the number is 120.0 and then zero is more. Can anyone help on this, thanks

Yunus Kocatas
  • 286
  • 2
  • 9
  • Seems to be a duplicate of https://stackoverflow.com/questions/20788320/how-to-convert-a-double-to-an-int-in-dart – Vincent Bitter Feb 03 '22 at 11:14
  • This really should not be solved using string tests. Use the modulo operator and integer division instead. – Ber Feb 03 '22 at 12:35

3 Answers3

3

You can use method for double to int;

double a = 8.5;
print(a.toInt())  // 8

Answer:

 while (factorial > 10 && factorial.toString().split('').last == "0") {
    factorial = (factorial / 10).toInt(); // Add toInt()

    answer++;
  }
Yasin Ege
  • 605
  • 4
  • 14
1

To convert a double to int, just use:

double x = 1.256;
print(x.toInt()); //this will print 1

I am not sure what you are asking in this question other than this.

Md. Kamrul Amin
  • 1,870
  • 1
  • 11
  • 33
1

Check the accepted answer to this Question: How to do Integer division in Dart?

Integer division in Dart has its own operator: ~/ as in

print(16 ~/ 3);
Ber
  • 40,356
  • 16
  • 72
  • 88