Solving the largest possible integer

Our problem is asking us to return the largest possible integer after adding a 5 among the digits. For example, when given the number 268 our expected output is 5268, and when given 670 we are expected to return 6750. When given 0 our output is 50, when given a negative number like -999 our output is expected to -5999.

In order for us to solve this problem, we must first plan where and why we will place our 5. In order for us to have the largest possible integer, we must look at the first integer. If the first integer is less than or equal to five, then in order for the integer to become the largest possible integer, we add the five to the beginning of the number. If the first integer is greater than 5 then we need to add our 5 after the first number. These are our base cases for solving this problem. Now, what about our negative numbers? Well, that is just our base cases flipped.

Here is my code for solving this problem.

const largestPossibleInteger = (N) => {let arr = []if (N >= 0) {arr = String(N).split('')if (arr[0] <= 5) {arr.unshift(5)} else {for (let i = 0; i < arr.length; i++) {if (arr[i] > 5) {continue;} else {arr.splice(i, 0, 5)break;}}}} else {let newN = Math.abs(N)arr = String(newN).split('')if (arr[0] >= 5) {arr.unshift(5)} else {for (let j = 0; j < arr.length; j++) {if (arr[j] < 5) {continue;} else {arr.splice(j, 0, 5)break;}}}arr.unshift("-")}return arr.join('')}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

HD Dave Buys Houses https://t.co/iZnuWV3TDU

CROSS ORIGIN RESOURCE SHARING (CORS) explained with example

Navigation and named routes in Flutter

HTML, Javascript, the DOM… oh and CSS

Dive into a Bootsrap React(js)-ion : react-bootstrap-table-next

5 Best Chrome Extensions for Web Developers

Upgrading React, Enzyme, and Typescript

Implementing GitHub OAuth with React and Rails

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Michael Horowitz

Michael Horowitz

More from Medium

How to get ahead in your twenties after college( irrespective of grades)

PSA: Participation Trophies Are Okay

Full of Art and Literature

Getting started on your DeFi adventure.