Created
April 4, 2019 06:20
-
-
Save Ahmah2009/91c88a07ea1f54db2f194d1ae2089757 to your computer and use it in GitHub Desktop.
640. Solve the Equation Leetcode
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
import "strings" | |
import "strconv" | |
func solveEquation(equation string) string { | |
eqnSides := strings.Split(equation, "=") | |
leftHandSide, rightHandSide := eqnSides[0], eqnSides[1] | |
lHV,lHx := getSideSum(leftHandSide) | |
rHV,rHx := getSideSum(rightHandSide) | |
if lHx == rHx && lHV == rHV{ | |
return "Infinite solutions" | |
} | |
if lHx == rHx { | |
return "No solution" | |
} | |
result := (rHV-lHV)/(lHx-rHx) | |
return "x="+strconv.Itoa(result) | |
} | |
func getSideSum(side string) (int, int){ | |
tempNumber := []byte {} | |
sum := 0 | |
xSum := 0 | |
for i:= range side{ | |
if side[i] == '-'|| side[i] == '+' { | |
num, err := strconv.Atoi(string(tempNumber)) | |
if err == nil{ | |
sum += num | |
}else{ | |
xSum += getXCoff(string(tempNumber)) | |
} | |
tempNumber = []byte{side[i]} | |
}else{ | |
tempNumber = append(tempNumber, side[i]) | |
} | |
} | |
num, err := strconv.Atoi(string(tempNumber)) | |
if err == nil{ | |
sum += num | |
}else{ | |
xSum += getXCoff(string(tempNumber)) | |
} | |
return sum,xSum | |
} | |
func getXCoff(s string)int{ | |
n := len(s) | |
if n==0{ | |
return 0 | |
} | |
if n == 1 { | |
return 1 | |
} | |
if n == 2 && (s[0] == '-' || s[0] == '+'){ | |
num, _ := strconv.Atoi(s[:n-1]+"1") | |
return num | |
} | |
fmt.Println(s) | |
num, _ := strconv.Atoi(s[:n-1]) | |
return num | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment