File tree Expand file tree Collapse file tree 2 files changed +111
-0
lines changed
Expand file tree Collapse file tree 2 files changed +111
-0
lines changed Original file line number Diff line number Diff line change 1+ ## :lion : Leetcode
2+
3+ ### String to Int - Atoi
4+
5+ ``` dart
6+ int myAtoi(String s) {
7+ // Base condition
8+ if (s.length < 1) {
9+ return 0;
10+ }
11+ // MAX and MIN values for integers
12+ final int max = 2147483647;
13+ final int min = -2147483648;
14+
15+ s = s.trim();
16+
17+ // Counter
18+ int i = 0;
19+ // Flag to indicate if the number is negative
20+ bool isNegative = s.startsWith("-");
21+ // Flag to indicate if the number is positive
22+ bool isPositive = s.startsWith("+");
23+
24+ if (isNegative) {
25+ i++;
26+ } else if (isPositive) {
27+ i++;
28+ }
29+
30+ // This will store the converted number
31+ double number = 0;
32+ // Loop for each numeric character in the sing iff numeric characters are leading
33+ // characters in the sing
34+ while (i < s.length &&
35+ s[i].codeUnitAt(0) >= '0'.codeUnitAt(0) &&
36+ s[i].codeUnitAt(0) <= '9'.codeUnitAt(0)) {
37+ number = number * 10 + (s[i].codeUnitAt(0) - '0'.codeUnitAt(0));
38+ i++;
39+ }
40+ // Give back the sign to the converted number
41+ number = isNegative ? -number : number;
42+ if (number < min) {
43+ return min;
44+ }
45+ if (number > max) {
46+ return max;
47+ }
48+ return number.round();
49+ }
50+ ```
Original file line number Diff line number Diff line change 1+ void main (List <String > args) {
2+ List <String > cases = [
3+ "42" ,
4+ " -42" ,
5+ "+-2" ,
6+ "4193 with words" ,
7+ "-91283472332" ,
8+ "00000-42a1234" ,
9+ "words and 987" ,
10+ "3.14159" ,
11+ ];
12+
13+ for (final testcase in cases) {
14+ print (myAtoi (testcase));
15+ }
16+ }
17+
18+ int myAtoi (String s) {
19+ // Base condition
20+ if (s.length < 1 ) {
21+ return 0 ;
22+ }
23+ // MAX and MIN values for integers
24+ final int max = 2147483647 ;
25+ final int min = - 2147483648 ;
26+
27+ s = s.trim ();
28+
29+ // Counter
30+ int i = 0 ;
31+ // Flag to indicate if the number is negative
32+ bool isNegative = s.startsWith ("-" );
33+ // Flag to indicate if the number is positive
34+ bool isPositive = s.startsWith ("+" );
35+
36+ if (isNegative) {
37+ i++ ;
38+ } else if (isPositive) {
39+ i++ ;
40+ }
41+
42+ // This will store the converted number
43+ double number = 0 ;
44+ // Loop for each numeric character in the sing iff numeric characters are leading
45+ // characters in the sing
46+ while (i < s.length &&
47+ s[i].codeUnitAt (0 ) >= '0' .codeUnitAt (0 ) &&
48+ s[i].codeUnitAt (0 ) <= '9' .codeUnitAt (0 )) {
49+ number = number * 10 + (s[i].codeUnitAt (0 ) - '0' .codeUnitAt (0 ));
50+ i++ ;
51+ }
52+ // Give back the sign to the converted number
53+ number = isNegative ? - number : number;
54+ if (number < min) {
55+ return min;
56+ }
57+ if (number > max) {
58+ return max;
59+ }
60+ return number.round ();
61+ }
You can’t perform that action at this time.
0 commit comments