```// SOLUTION 1 - MY SOLUTION (RUNTIME - 92MS, MEMORY - 40.7MB)
var reverse = function(x) {
// set variable that converts integer to a string, splits into an arr, reverses arr, and rejoins into a string
const temp = x.toString().split("").reverse().join("");
// converts string back into an integer
let reversedNum = parseInt(temp);

// using original argument, check if reversed number needs to be a positive or negative value
if (Math.sign(x) === -1) reversedNum = reversedNum * -1

// check to see if reversed integer fits within listed 32-bit contraint
if (Math.pow(-2, 31) > reversedNum || reversedNum > Math.pow(2, 31)) return 0;
else return reversedNum
};

// SOLUTION 2 (BEST RUNTIME - 60MS)
var reverse = function(x) {
const limit = 2147483648;
const reversedNum = parseFloat(x.toString().split("").reverse().join(""))
return reversedNum > limit ? 0 : reversedNum * Math.sign(x);
};

// SOLUTION 3 (RUNTIME - 60MS)
var reverse = function(x) {
const sign = x < 0 ? -1 : 1;
const positiveX = x * sign;
const y = parseInt(positiveX.toString().split('').reverse().join('')) * sign;
const absoluteY = y * sign;

//0x7FFFFFFF is a number in hexadecimal (2,147,483,647 in decimal) that represents the maximum positive value for a 32-bit signed binary integer
return absoluteY <= (y < 0 ? 0x80000000 : 0x7FFFFFFF) ? y : 0;
};```
```// SOLUTION 1 - MY SOLUTION (RUNTIME - 104MS, 45.9 MB)
var reverseString = function(s) {
s.reverse()
};

// SOLUTION 2 (BEST RUNTIME - 80MS)
var reverseString = function(s) {
// declared here to set a stable loop constant
// sets the indecies (ie. s.length = 6, indecies -> 0-5)
let length = s.length - 1;

//a will store value of current str so it isn't lost during reassignment
let a;

//loop will only need to reach the midpoint to reverse string
for(let i = Math.floor(length/2); i >= 0; i--){
a = s[i];
s[i] = s[Math.abs(i - length)];
s[Math.abs(i - length)] = a;
}
return s;
};

// SOLUTION 3 (RUNTIME - 108MS)
var reverseString = function(s) {
// set up a for loop with 'i' only iteration up to half the length of 's'
for(let i = 0; i < s.length / 2; i++) {
let temp = s[s.length-1-i];
s[s.length-1-i] = s[i];
s[i] = temp;
}
};```
star

Wed Sep 15 2021 13:34:13 GMT+0000 (UTC) https://leetcode.com/submissions/detail/555353674/?from=explore&item_id=880

#javascript #strings #reversal #integers
star

Tue Sep 14 2021 13:26:49 GMT+0000 (UTC) https://leetcode.com/submissions/detail/554777828/?from=explore&item_id=879

#javascript #strings #loops #reversal