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
CodePudding user response:
- transform the number into an String using
String stringValue = x.toString();
- create an array from each char using
List<String> result = stringValue.split('');
- sum each number transforming back using
int.parse(result)
void main(){
int x = 1992;
String stringValue = x.toString();
List<String> result = stringValue.split('');
int sum = 0;
for(int i = 0 ; i < result.length; i ) {
int value = int.parse(result[i]);
sum = sum value;
}
print(sum);
}
Result: 21
CodePudding user response:
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