Created
October 3, 2023 07:34
-
-
Save jimmycann/f2642eab766bd551437b9c4ad3c7ef25 to your computer and use it in GitHub Desktop.
Remove Optimal 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
// Receive a number as an argument 15956 for example between the range of -99995 and 99995. | |
// There are a number of 5s in any given number. For a given number I need to figure out the highest | |
// possible value of the number when one '5' is removed. | |
func removeOptimal5(n int) int { | |
// Convert int to string | |
s := strconv.Itoa(n) | |
// Create a variable to keep track of the maximum value | |
maxValue := -99995 | |
// Loop through the string and try removing each '5' | |
for idx := 0; idx < len(s); idx++ { | |
if s[idx] == '5' { | |
// Create a new string by removing the current '5' | |
newStr := s[:idx] + s[idx+1:] | |
// Convert the new string back to an integer | |
newInt, _ := strconv.Atoi(newStr) | |
// Update the maximum value if the current value is greater | |
if newInt > maxValue { | |
maxValue = newInt | |
} | |
} | |
} | |
return maxValue | |
} | |
func main() { | |
fmt.Println(removeOptimal5(15956)) // Should print 1956 | |
fmt.Println(removeOptimal5(15256)) // Should print 1526 | |
fmt.Println(removeOptimal5(-15956)) // Should print -1596 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment