640. Solve the Equation

LeetCode medium оригинал: C# #array #csharp #leetcode #medium #string #two-pointers

Решите заданное уравнение и верните значение 'x' в виде строки "x=

C# решение

сопоставлено/оригинал
using System;
using System.Text.RegularExpressions;
public class Solution {
    public string SolveEquation(string equation) {
        string[] sides = equation.Split(new char[] { '=' });
        int[] left = Parse(sides[0]);
        int[] right = Parse(sides[1]);
        
        int coeff = left[0] - right[0];
        int constPart = right[1] - left[1];
        
        if (coeff == 0) {
            return constPart == 0 ? "Infinite solutions" : "No solution";
        }
        return "x=" + (constPart / coeff);
    }
    private int[] Parse(string s) {
        int coeff = 0, constPart = 0, sign = 1, num = 0;
        int i = 0;
        while (i < s.Length) {
            if (s[i] == '+') {
                sign = 1;
                i++;
            } else if (s[i] == '-') {
                sign = -1;
                i++;
            } else if (char.IsDigit(s[i])) {
                num = 0;
                while (i < s.Length && char.IsDigit(s[i])) {
                    num = num * 10 + (s[i] - '0');
                    i++;
                }
                if (i < s.Length && s[i] == 'x') {
                    coeff += sign * num;
                    i++;
                } else {
                    constPart += sign * num;
                }
            } else if (s[i] == 'x') {
                coeff += sign;
                i++;
            }
        }
        return new int[]{coeff, constPart};
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public string SolveEquation(string equation) {
        vector<string> sides = equation.Split(new char[] { '=' });
        vector<int>& left = Parse(sides[0]);
        vector<int>& right = Parse(sides[1]);
        
        int coeff = left[0] - right[0];
        int constPart = right[1] - left[1];
        
        if (coeff == 0) {
            return constPart == 0 ? "Infinite solutions" : "No solution";
        }
        return "x=" + (constPart / coeff);
    }
    private vector<int>& Parse(string s) {
        int coeff = 0, constPart = 0, sign = 1, num = 0;
        int i = 0;
        while (i < s.size()) {
            if (s[i] == '+') {
                sign = 1;
                i++;
            } else if (s[i] == '-') {
                sign = -1;
                i++;
            } else if (char.IsDigit(s[i])) {
                num = 0;
                while (i < s.size() && char.IsDigit(s[i])) {
                    num = num * 10 + (s[i] - '0');
                    i++;
                }
                if (i < s.size() && s[i] == 'x') {
                    coeff += sign * num;
                    i++;
                } else {
                    constPart += sign * num;
                }
            } else if (s[i] == 'x') {
                coeff += sign;
                i++;
            }
        }
        return new int[]{coeff, constPart};
    }
}

Java решение

сопоставлено/оригинал
public class Solution {
    public String solveEquation(String equation) {
        String[] sides = equation.split("=");
        int[] left = parse(sides[0]);
        int[] right = parse(sides[1]);
        
        int coeff = left[0] - right[0];
        int constPart = right[1] - left[1];
        
        if (coeff == 0) {
            return constPart == 0 ? "Infinite solutions" : "No solution";
        }
        return "x=" + (constPart / coeff);
    }

    private int[] parse(String s) {
        int coeff = 0, constPart = 0, sign = 1, num = 0;
        int i = 0;
        while (i < s.length()) {
            if (s.charAt(i) == '+') {
                sign = 1;
                i++;
            } else if (s.charAt(i) == '-') {
                sign = -1;
                i++;
            } else if (Character.isDigit(s.charAt(i))) {
                num = 0;
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + (s.charAt(i) - '0');
                    i++;
                }
                if (i < s.length() && s.charAt(i) == 'x') {
                    coeff += sign * num;
                    i++;
                } else {
                    constPart += sign * num;
                }
            } else if (s.charAt(i) == 'x') {
                coeff += sign;
                i++;
            }
        }
        return new int[]{coeff, constPart};
    }
}

JavaScript решение

сопоставлено/оригинал
var solveEquation = function(equation) {
    const parse = (s) => {
        let coeff = 0, constPart = 0, sign = 1, num = 0;
        let i = 0;
        while (i < s.length) {
            if (s[i] === '+') {
                sign = 1;
                i++;
            } else if (s[i] === '-') {
                sign = -1;
                i++;
            } else if (s[i] >= '0' && s[i] <= '9') {
                num = 0;
                while (i < s.length && s[i] >= '0' && s[i] <= '9') {
                    num = num * 10 + (s[i] - '0');
                    i++;
                }
                if (i < s.length && s[i] === 'x') {
                    coeff += sign * num;
                    i++;
                } else {
                    constPart += sign * num;
                }
            } else if (s[i] === 'x') {
                coeff += sign;
                i++;
            }
        }
        return [coeff, constPart];
    };

    const [left, right] = equation.split('=');
    const [leftCoeff, leftConst] = parse(left);
    const [rightCoeff, rightConst] = parse(right);

    const coeff = leftCoeff - rightCoeff;
    const constPart = rightConst - leftConst;

    if (coeff === 0) {
        return constPart === 0 ? "Infinite solutions" : "No solution";
    }
    return `x=${constPart / coeff}`;
};

Python решение

сопоставлено/оригинал
def solveEquation(equation: str) -> str:
    def parse(equ):
        coeff, const = 0, 0
        num, sign = 0, 1
        i = 0
        while i < len(equ):
            if equ[i] == '+':
                sign = 1
                i += 1
            elif equ[i] == '-':
                sign = -1
                i += 1
            elif equ[i].isdigit():
                num = 0
                while i < len(equ) and equ[i].isdigit():
                    num = num * 10 + int(equ[i])
                    i += 1
                if i < len(equ) and equ[i] == 'x':
                    coeff += sign * num
                    i += 1
                else:
                    const += sign * num
            elif equ[i] == 'x':
                coeff += sign
                i += 1
        return coeff, const
    
    left, right = equation.split('=')
    left_coeff, left_const = parse(left)
    right_coeff, right_const = parse(right)
    
    coeff = left_coeff - right_coeff
    const = right_const - left_const
    
    if coeff == 0:
        return "Infinite solutions" if const == 0 else "No solution"
    return f"x={const // coeff}"

Go решение

сопоставлено/оригинал
package main

import (
  "fmt"
  "strconv"
  "strings"
)

func solveEquation(equation string) string {
  parse := func(s string) (int, int) {
    coeff, constPart, sign, num := 0, 0, 1, 0
    i := 0
    for i < len(s) {
      if s[i] == '+' {
        sign = 1
        i++
      } else if s[i] == '-' {
        sign = -1
        i++
      } else if s[i] >= '0' && s[i] <= '9' {
        num = 0
        for i < len(s) && s[i] >= '0' && s[i] <= '9' {
          num = num*10 + int(s[i]-'0')
          i++
        }
        if i < len(s) && s[i] == 'x' {
          coeff += sign * num
          i++
        } else {
          constPart += sign * num
        }
      } else if s[i] == 'x' {
        coeff += sign
        i++
      }
    }
    return coeff, constPart
  }

  left, right := equation[:strings.Index(equation, "=")], equation[strings.Index(equation, "=")+1:]
  leftCoeff, leftConst := parse(left)
  rightCoeff, rightConst := parse(right)

  coeff := leftCoeff - rightCoeff
  constPart := rightConst - leftConst

  if coeff == 0 {
    if constPart == 0 {
      return "Infinite solutions"
    }
    return "No solution"
  }
  return "x=" + strconv.Itoa(constPart/coeff)
}

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.