Skip to content

Commit

Permalink
[Reverse Int] StephenGrider#3 Completed
Browse files Browse the repository at this point in the history
  • Loading branch information
Brett Dawidowski committed Mar 24, 2019
1 parent 9b3b5f2 commit 071c47a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
5 changes: 1 addition & 4 deletions exercises/palindrome/index.js
Expand Up @@ -36,7 +36,4 @@ function palindrome(str) {

}

module.exports = palindrome;



module.exports = palindrome;
43 changes: 42 additions & 1 deletion exercises/reverseint/index.js
Expand Up @@ -8,6 +8,47 @@
// reverseInt(-15) === -51
// reverseInt(-90) === -9

function reverseInt(n) {}
function reverseInt(n) {

// #1

// 1.1 Number to String
// 1.2 Splits String char into Array items
// 1.3 Reverse items in the Array
// 1.4 Join/Adds items on Array back into String
const rev = n
.toString()
.split('')
.reverse()
.join('');

// Parse String into Number them multiples by 1 or -1 depending on
// if the orginal number was postive or negative
return parseInt(rev) * Math.sign(n);


// # 2
// Uses Array prototypes to solve this problem
// This approach is a lot easier to follow / read

// Determine if the entry is negative or postive
const isNeg = Math.sign(n) < 0 ? true : false;

// Converts Number to String then splits char into Array items
const beginArr = n.toString().split('');

// Removes '-' neg sign from begining of Array
if (isNeg) beginArr.shift();

// Reverses items in the Array
const reverseArr = beginArr.reverse();

// Inserts '-' neg sign to the begining Array
if (isNeg) reverseArr.unshift('-');

// Converst String/Array back to Number
// Note: Removes 0s in the begining
return parseInt(reverseArr.join(''));
}

module.exports = reverseInt;

0 comments on commit 071c47a

Please sign in to comment.