Search code examples
flutterdartflutter-layout

Flutter find the sum of digits of int value


I want to find the sum of the digits of the number entered in Flutter. I want to encode this algorithm.

for example x=1992 result=1+9+9+2=21

how can i do this with flutter


Solution

  • You can do in this way.

    import 'dart:io';
     
    void main() {
      print('Enter X');
      int X = int.parse(stdin.readLineSync()!);
     
      int result = 0;
      for (int i = X; i > 0; i = (i / 10).floor()) {
        result += (i % 10);
      }
     
      print('Sum of digits\n$result');
    }
    

    Output

    Enter X 123456 Sum of digits 21