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;
        }
      }
    }
  • 相关阅读:
    1210 BBS admin后台管理及侧边栏筛选个人站点
    1209 BBS 登录
    更换 npm 源国内镜像 cnpm
    Linux软件管理
    apt-get / yum 软件安装源(国内)
    修改pip源为国内镜像源(加速下载)
    修改浏览器搜索引擎:网址应该如何填写
    如何根据实际问题选择一个合适的数学模型
    安装向量和矩阵运算库函数
    配置编译器(GCC和GFortran)
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10278327.html
Copyright © 2011-2022 走看看