zoukankan      html  css  js  c++  java
  • LC 640. Solve the Equation

    Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

    If there is no solution for the equation, return "No solution".

    If there are infinite solutions for the equation, return "Infinite solutions".

    If there is exactly one solution for the equation, we ensure that the value of x is an integer.

    Example 1:

    Input: "x+5-3+x=6+x-2"
    Output: "x=2"
    

    Example 2:

    Input: "x=x"
    Output: "Infinite solutions"
    

    Example 3:

    Input: "2x=x"
    Output: "x=0"
    

    Example 4:

    Input: "2x+3x-6x=x+2"
    Output: "x=-1"
    

    Example 5:

    Input: "x=x+2"
    Output: "No solution"

    Runtime: 4 ms, faster than 99.39% of Java online submissions for Solve the Equation.

    class Solution {
      public static int[] mergenumber(String s){
        int cnt = 0, tmpcnt = 0, xval = 0, constval = 0, prev = 1;
        if(s.charAt(tmpcnt) == '+' || s.charAt(tmpcnt) == '-'){
          cnt = ++tmpcnt;
          prev = s.charAt(cnt-1) == '+' ? 1 : -1;
        }
        while(cnt < s.length()){
          while(tmpcnt < s.length() && s.charAt(tmpcnt) != '+' && s.charAt(tmpcnt) != '-'){
            tmpcnt++;
          }
          if(s.charAt(tmpcnt-1) == 'x'){
            if(tmpcnt -1 > cnt) xval += prev * Integer.parseInt(s.substring(cnt, tmpcnt-1));
            else xval += prev * 1;
          }else constval += prev * Integer.parseInt(s.substring(cnt, tmpcnt));
          if(tmpcnt == s.length()) break;
          cnt = ++tmpcnt;
    
          prev = s.charAt(tmpcnt-1) == '+' ? 1 : -1;
        }
        int[] ret = {xval, constval};
        return ret;
      }
      public static String solveEquation(String equation) {
        int idx = 0;
    
        for(; idx<equation.length(); idx++){
          if(equation.charAt(idx) == '=') break;
        }
        int[] left = mergenumber(equation.substring(0,idx));
    //    System.out.println(left[0]);
    //    System.out.println(left[1]);
        int[] right = mergenumber(equation.substring(idx+1));
    //    System.out.println(right[0]);
    //    System.out.println(right[1]);
        if(left[0] == right[0]){
          if (left[1] == right[1]) return "Infinite solutions";
          else return "No solution";
        } else {
          int ret = -1 * (right[1] - left[1]) / (right[0] - left[0]);
          String rets = "x=" + String.valueOf(ret);
          return rets;
        }
      }
    }
  • 相关阅读:
    009-Python-面向对象
    008-Python-模块
    007-Python函数-装饰器
    006-Python函数
    005-Python字典
    003-python列表
    PyCharm之python书写规范--消去提示波浪线
    001-python基础
    Java基础总结(一)
    High ASCII字符从bat文件到dos控制台的转化问题
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10278327.html
Copyright © 2011-2022 走看看