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;
        }
      }
    }
  • 相关阅读:
    JS数组常用方法参考---5、sort方法
    JS数组常用方法---1、课程介绍
    JS数组常用方法参考---4、unshift方法
    JS数组常用方法参考---3、队列对应的方法
    ES6课程---12、面向对象
    legend3---30、不同类型的网站打包方案
    数据库Sharding的基本思想和切分策略
    用sharding技术来扩展你的数据库(一)sharding 介绍
    什么是Scale Up和Scale Out?
    淘宝网采用什么技术架构来实现网站高负载的
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10278327.html
Copyright © 2011-2022 走看看