2018笔试题——求一元一次方程的解

给出一个没有简化的一元一次方程的解,如果方程没有解,返回“No solution”;如果方程有无穷解,返回“Infinite solutions”。如果这个方程只有一个解,返回“x=?”,其中?代表解的数值,题目保证方程的解是整数。

示例1:

输入:

2x+5-3+x=6+x-2

输出:

x=1


示例2:

输入:

-2x=x-3x+7

输出:

No solution


示例3:

输入:

x+7=5+x+2

输出:

Infinite solutions


代码:

import java.util.Scanner;

public class Equation {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String ss = in.nextLine();
		String[] s = ss.split("=");//将等式两边的分开处理
		int a=0;	//代表累积常数
		int b=0;	//代表累积系数
		//等式左边
		a += f(s[0])[0];
		b += f(s[0])[1];
		//等式右边
		a -= f(s[1])[0];
		b -= f(s[1])[1];
		
		if(a==0)
			System.out.println("Infinite solutions");
		else if(b==0){
			System.out.println("No Solution!");
		}else{
			System.out.println(-a/b);	//注意打印时候的符号
		}
	}
	
	public static int[] f(String s){
		int[] t= new int[2];	//t[0]存常数,t[1]存x前面的系数
		int e=0,f=0;	//f取符号,e取当前读到的数字
		if(s.substring(0, 1).equals("-"))	//先判断第一位是整数还是负数
			f=-1;
		else
			f=1;
		int bb=0;	//bb用于存放一个数
		for(int i=0;i





你可能感兴趣的:(Algorithm)