求方程的解 Solve the Equation

為什么80%的碼農都做不了架構師?>>> ??hot3.png

問題:

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"

解決:

① 解方程。難點在于處理字符串,如何將x的系數合并起來,將常數合并起來,化簡成ax=b的形式來求解。

例:
x + 5 -2x = 6-3x;
leftPart:tokens= {x,+ 5,-2x}; 系數為x = 1-2 = -1; 常數= 5;
rightPart:tokens = {6,-3x}; 系數為x = -3; 常數= 6;

最終結果=(6-5)/(-1 - ( - 3))

class Solution { //12ms
? ? public String solveEquation(String equation) {
? ? ? ? String[] parts = equation.split("=");
? ? ? ? int[] leftPart = evaluate(parts[0]);
? ? ? ? int[] rightPart = evaluate(parts[1]);
? ? ? ? if (leftPart[0] == rightPart[0] && leftPart[1] == rightPart[1]){
? ? ? ? ? ? return "Infinite solutions";
? ? ? ? }else if (leftPart[0] == rightPart[0]){
? ? ? ? ? ? return "No solution";
? ? ? ? }
? ? ? ? return "x=" + (rightPart[1] - leftPart[1]) / (leftPart[0] - rightPart[0]);
? ? }
? ? public int[] evaluate(String str){
? ? ? ? String[] tokens = str.split("(?=[+-])");//()匹配組; ?=匹配并包含在res中; [+ - ]表示+或 - ;
? ? ? ? int[] res = new int[2];//記錄系數為x; 系數為常數
? ? ? ? for (String token : tokens){
? ? ? ? ? ? if (token.equals("+x") || token.equals("x")){
? ? ? ? ? ? ? ? res[0] ++;// x表示1x
? ? ? ? ? ? }else if (token.equals("-x")){
? ? ? ? ? ? ? ? res[0] --;
? ? ? ? ? ? }else if (token.contains("x")){
? ? ? ? ? ? ? ? res[0] += Integer.parseInt(token.substring(0,token.length() - 1));
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? res[1] += Integer.parseInt(token);
? ? ? ? ? ? }

? ? ? ? }
? ? ? ? return res;
? ? }
}

② 在discuss中看到的,思路相同。

class Solution { //9ms
? ? public String solveEquation(String equation) {
? ? ? ? if(equation == null || equation.length() == 0) return "No solution";
? ? ? ? String[] sides = equation.split("=");
? ? ? ? int[] left = parse(sides[0]), right = parse(sides[1]);
? ? ? ? if(left[0] == right[0]) {
? ? ? ? ? ? if(left[1] == right[1]) return "Infinite solutions";
? ? ? ? ? ? return "No solution";
? ? ? ? }
? ? ? ? int val = (right[1] - left[1]) / (left[0] - right[0]);
? ? ? ? return "x=" + val;
? ? }
? ??
? ? private int[] parse(String s) {
? ? ? ? int sign = 1, val = 0;
? ? ? ? int[] res = new int[2];
? ? ? ? for(int i = 0; i < s.length(); i ++) {
? ? ? ? ? ? char c = s.charAt(i);
? ? ? ? ? ? if(c == 'x') {
? ? ? ? ? ? ? ? if(i == 0) res[0] ++;
? ? ? ? ? ? ? ? else if(s.charAt(i-1) == '-' || s.charAt(i-1) == '+') res[0] += sign;
? ? ? ? ? ? ? ? else res[0] += sign * val;
? ? ? ? ? ? ? ? val = 0;
? ? ? ? ? ? } else if(c == '-' || c == '+') {
? ? ? ? ? ? ? ? res[1] += sign * val;
? ? ? ? ? ? ? ? val = 0;
? ? ? ? ? ? ? ? sign = c == '-' ? -1 : 1;
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? val = val * 10 + c - '0';
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? res[1] += sign * val;
? ? ? ? return res;
? ? }
}

轉載于:https://my.oschina.net/liyurong/blog/1606460

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/539632.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/539632.shtml
英文地址,請注明出處:http://en.pswp.cn/news/539632.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[C#學習] DataAdapter.Fill()分頁

查詢結果分頁是以較小數據子集&#xff08;即頁&#xff09;的形式返回查詢結果的過程。 它通常用于以易于管理的小塊形式向用戶顯示結果。DataAdapter 提供了通過 Fill 方法的重載來僅返回一頁數據的功能。 但是&#xff0c;對于大量的查詢結果&#xff0c;它可能并不是首選的…

java流讀取字符串_javaIO之字符流是怎么讀取的?

最近在看io相關的知識&#xff0c;遇到一些小問題&#xff0c;以下有例子來說明問題&#xff1a;比如&#xff1a;12345 是一個十進制數根據ASCII碼找到是 &#xff1a;二進制 00110001 00110010 00110011 00110100 00110101十進制4950515253十六進制 0x310x320x330x340x35文件…

什么是mybatis,mybatis有什么特點

jdbc開發優缺點&#xff1a;http://blog.csdn.net/zengmingen/article/details/51180796 hibernate開發優缺點&#xff1a;http://blog.csdn.net/zengmingen/article/details/51180805 1&#xff09;基于上述二種支持&#xff0c;我們需要在中間找到一個平衡點呢&#xff1f;結…

簡易RPC框架實現

寫在最前面 PRC(Remote Procedure Call) 遠程過程調用。通俗的講就是程序通過RPC框架調用遠程主機的方法就如同調用本地方法一樣。Dubbo就是這樣一個Rpc框架&#xff0c;本文主要參考Dubbo的設計思路&#xff0c;簡易實現了Rpc框架。 本文涉及到知識點包括&#xff1a; Jdk 動態…

kafka java獲取topic_通過編程方式獲取Kafka中Topic的Metadata信息

如果我們需要通過編程的方式來獲取到TopicMetadataRequest請求到 def findLeader(topic: String): Unit {val consumer connect("www.iteblog.com", 9092)val req TopicMetadataRequest(TopicMetadataRequest.CurrentVersion,0, kafkaGroupId, List(topic))val to…

redis java 遍歷key_java遍歷讀取整個redis數據庫實例

redis提供了靈活的數據查詢方式&#xff0c;最牛的就是key的搜索支持正則表達式。jedis.keys(“*”);表示搜索所有keyjedis.keys(“abc*”)表示搜索開頭為abc的key數據遍歷了key就能遍歷到value。其實就是一個setRedisDO rd new RedisDO();rd.open();Set s rd.jedis.keys(&qu…

js學習

為什么80%的碼農都做不了架構師&#xff1f;>>> /* my code */ var gArrSpell [ 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 999999, AAAA, bbbb, cccc, dddd, eeee, fffff ];var gArrSplDmg [11,12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24…

代碼在eclipse下不報錯,在doc命令行下報錯--jar file和runable jar file

今天開發一個小工具&#xff0c;引用了Log4j&#xff0c;來記錄日志&#xff0c;在eclipse下運行&#xff0c;代碼正常&#xff0c;打包成jar放到doc命令行下運行報錯&#xff1a; Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/logging/…

gradle java ide_使用Gradle構建Java項目

使用Gradle構建Java項目這個手冊將通過一個簡單的Java項目向大家介紹如何使用Gradle構建Java項目。我們將要做什么&#xff1f;我們將在這篇文檔航中創建一個簡單的Java項目&#xff0c;然后使用Gradle構建它。需要準備什么&#xff1f;預留15分鐘空閑時間一件稱手的兵器(你最喜…

小馬激活軟件下載,當心偽小馬,有病毒

官方的小馬激活軟件已經停止更新了&#xff0c;下文是官方停更公告。 http://www.pccppc.com/xiaomajihuo-html 所以小馬oem7以后的都不是官方的&#xff0c;包含病毒。重裝系統后&#xff0c;一般是先激活系統&#xff0c;再安裝殺毒軟件&#xff0c;這就給“偽小馬激活工具”…

truncate,delete,drop之間的區別

TRUNCATE TABLE 在功能上與不帶 WHERE 子句的 DELETE 語句相同&#xff1a;二者均刪除表中的全部行。 但 TRUNCATE TABLE 比 DELETE 速度快&#xff0c;且使用的系統和事務日志資源少。 DELETE 語句每次刪除一行&#xff0c;并在事務日志中為所刪除的每行記錄一項。 TRUNCATE…

三張圖搞懂JavaScript的原型對象與原型鏈

對于新人來說&#xff0c;JavaScript的原型是一個很讓人頭疼的事情&#xff0c;一來prototype容易與__proto__混淆&#xff0c;二來它們之間的各種指向實在有些復雜&#xff0c;其實市面上已經有非常多的文章在嘗試說清楚&#xff0c;有一張所謂很經典的圖&#xff0c;上面畫了…

python partial_如何在python多處理模塊中使用partial函數?

下面是我如何解決這個問題的一個簡單例子from functools import partialfrom multiprocessing import Pooldef VariadicLifter(func, args):return func(*args)def func(x,y,z,a):return x2*y3*z4*aif __name__ __main__:func_ partial( func, 500, 1007)lfunc_ partial( Va…

Mybatis中resultMap

MyBatis中在查詢進行select映射的時候&#xff0c;返回類型可以用resultType&#xff0c;也可以用resultMap&#xff0c;resultType是直接 表示返回類型的&#xff0c;而resultMap則是對外部ResultMap的引用&#xff0c;但是resultType跟resultMap不能同時存在。 1.resultType …

超簡單的mysql多實例布置

一、基本概念mysql下載&#xff1a;http://mirrors.sohu.com/mysql/MySQL-5.5/1、MySQL多實例就是在一臺機器上面開啟多個不同的端口&#xff0c;運行多個MySQL服務進程。這些MySQL多實例公用一套安裝程序&#xff0c;使用不同的(也可以是相同的)配置文件&#xff0c;啟動程序&…

java程序設計計算器_Java程序設計計算器(含代碼)

Java程序課程設計任務書實用性計算器的設計與開發1、主要內容&#xff1a;開發一個實用型的計算器程序&#xff0c;實現基本的計算功能同時并進行相應的功能拓展&#xff0c;使其具更加人性化的功能。我們可以用其進行相應的計算功能來方便我們的學習&#xff0c;代替我們進行一…

mybatis配置insert/update/delete同一個模板

insert&#xff0c;update&#xff0c;delete標簽只是一個模板&#xff0c;在操作時是以sql語句為核心的&#xff0c; 即在做增/刪/改時&#xff0c;insert/update/delete便簽可以通用&#xff0c; 但做查詢時只能用 select 標簽 提倡什么操作就用什么標簽 這就是為什么 ex…

Mybatis配置文件resultMap映射啥時候可寫可不寫?

1、student實體類 public class Student {private Integer id;//編號private String name;//姓名private Double sal;//薪水public Student(){}public Student(Integer id, String name, Double sal) {this.id id;this.name name;this.sal sal;}public Integer getId() {ret…

arithmetic java_Java:Arithmetic

好吧&#xff0c;事實上你有方法設置變量叫get - 這顯然不是一個好主意&#xff0c;并且沒有縮進......但它應該有效。但是&#xff0c;你還沒有展示出你是如何使用它的。也許你實際上并沒有被稱為setter方法&#xff1f;以下是相同代碼但具有不同名稱的示例&#xff0c;以及使…

網絡框架 Retrofit(三)

簡單實現Retrofit&#xff08;替代Okhttp&#xff09; 1.定義注解參數 Documented Target(PARAMETER) Retention(RUNTIME) public interface Field {String value(); } 復制代碼Documented Target(METHOD) Retention(RUNTIME) public interface Get {String value() default &q…