Skip to content

Commit b3ed4e8

Browse files
Update README.md
1 parent 8c10004 commit b3ed4e8

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

README.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,66 @@ return s.substring(start,end+1);//output [start,end]
187187

188188

189189

190+
191+
192+
193+
194+
195+
196+
197+
198+
199+
200+
201+
202+
<details>
203+
<summary> <strong>7.Reverse Integer</strong> </summary>
204+
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
205+
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
206+
```typescript
207+
Example 1:
208+
Input: x = 123
209+
Output: 321
210+
211+
Example 2:
212+
Input: x = -123
213+
Output: -321
214+
215+
Example 3:
216+
Input: x = 120
217+
Output: 21
218+
219+
220+
Constraints:
221+
-231 <= x <= 231 - 1
222+
```
223+
<!--module 7 code-->
224+
<details>
225+
<summary><strong>See solution</strong></summary>
226+
227+
```typescript
228+
function reverse(x:number):number {
229+
let reversed:number = 0;
230+
const sign:number = x < 0 ? -1 : 1;
231+
x = Math.abs(x);
232+
while (x > 0) { //x=123; digit=0; x=12; digit=3; x=1; digit=32;
233+
const digit:number = x % 10;//123 //digit = 3; digit = 2; digit = 1%10 = 1;
234+
reversed = (reversed * 10) + digit; //(0) + 3; (3*10) + 2 = 32; (32*10) + 1 = 321
235+
x = Math.floor(x / 10); //123/10 = 12.3 => 12; 12/10 = 1.2 = 1; 1/10 = 0(floor) end
236+
}
237+
reversed *= sign;
238+
// reversed < -2147483648 || reversed > 2147483647
239+
if (reversed < Math.pow(-2, 31) || reversed > (Math.pow(2, 31) - 1)) {
240+
return 0;
241+
}
242+
return reversed;
243+
244+
}
245+
```
246+
247+
</details><!--module 7 code ends-->
248+
</details><!--module 7 ends-->
249+
190250

191251

192252

0 commit comments

Comments
 (0)