如:
输入字符串:"1+2+3" 输出:"6"
输入字符串:"1+2-3" 输出:"0"
输入字符串:"-1+2+3" 输出:"4"
输入字符串:"1" 输出:"1"
输入字符串:"-1" 输出:"-1"
已知条件:输入的运算都是整数运算,且只有加减运算
要求:输出为String类型,不能使用内建的eval()函数
数据范围:计算过程中所有值满足 ,输入的字符串长度满足
输入字符串:"1+2+3"
输出:"6"
1+2+3
6
py2 作弊解法
print input()
#include <bits/stdc++.h> int n, len, sum, f, i; char s[110]; int main() { scanf("%d%s", &n, s), len = strlen(s); while (n += f ? sum : -sum, sum = 0, f = (s[i] == '+'), i < len) while (isdigit(s[++i])) sum = sum * 10 + s[i] - '0'; printf("%d", n); }
#include<iostream> #include<sstream> using namespace std; int main(){ string s; cin>>s; stringstream ss(s); int mid,count=0; while(ss>>mid){ count+=mid; } cout<<count; return 0; }
import java.util.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); String str = in.nextLine(); int res = 0, start = 0, pos=1; for(; pos<str.length(); pos++){ if(str.charAt(pos)=='+' || str.charAt(pos)=='-'){ res += Integer.parseInt(str.substring(start, pos)); start = pos; } } res += Integer.parseInt(str.substring(start, pos)); System.out.println(res); in.close(); } }
// 考虑数值溢出的情况 #include <iostream> #include <string> using namespace std; string addStr(string& str1, string& str2) { string result; int pre = 0; int i = str1.size() - 1; int j = str2.size() - 1; while(i >= 0 && j >= 0) { int sum = (str1[i] - '0') + (str2[j] - '0') + pre; char tempCh = sum % 10 + '0'; pre = sum / 10; result.insert(result.begin(), tempCh); i--; j--; } while(i >= 0) { int sum = str1[i] - '0' + pre; char tempCh = sum % 10 + '0'; pre = sum / 10; result.insert(result.begin(), tempCh); i--; } while(j >= 0) { int sum = str2[j] - '0' + pre; char tempCh = sum % 10 + '0'; pre = sum / 10; result.insert(result.begin(), tempCh); j--; } if(pre != 0) { result.insert(result.begin(), '1'); } return result; } string subStr(string& str1, string& str2) { string bigStr, smallStr; int flag = 0; // 为0表示相减为正数,为1表示相减为负数 if(str1.size() == str2.size()) { if(str1 < str2) { bigStr = str2; smallStr = str1; flag = 1; } else if(str1 == str2) { return string("0"); } else { bigStr = str1; smallStr = str2; } } else if(str1.size() < str2.size()) { bigStr = str2; smallStr = str1; flag = 1; } else { bigStr = str1; smallStr = str2; } int pre = 0; int i = bigStr.size() - 1; int j = smallStr.size() - 1; string result; while(i >= 0 && j >= 0) { if(pre == 1) { if(bigStr[i] == '0') { bigStr[i] = '9'; pre = 1; } else { bigStr[i] = static_cast<char>(bigStr[i] - '1' + '0'); } } if(bigStr[i] >= smallStr[j]) { //result.push_front(bigStr[i] - smallStr[j] + '0'); result.insert(result.begin(), bigStr[i] - smallStr[j] + '0'); } else { pre = 1; int num1 = bigStr[i] - '0' + 10; int num2 = smallStr[j] - '0'; //result.push_front(num1 - num2 + '0'); result.insert(result.begin(), num1 - num2 + '0'); } i--; j--; } while(i >= 0) { if(pre == 1) { if(bigStr[i] == '0' && i == 0) break; if(bigStr[i] == '0') { bigStr[i] = '9'; pre = 1; } else { bigStr[i] = static_cast<char>(bigStr[i] - '1' + '0'); } } //result.push_front(bigStr[i]); result.insert(result.begin(), bigStr[i]); i--; } int k = 0; while(result[k] != '\0') { if(result[k] != '0') break; else if(result[k] == '0') { result.erase(result.begin()); } } if(flag == 1) result.insert(result.begin(), '-'); return result; } int main() { string str; cin >> str; string str1; int i = 0; while(i < str.size()) { if(i != 0 && (str[i] == '-' || str[i] == '+')) break; str1 += str[i]; i++; } string str2; char preOp = '\0'; while(i <= str.size()) { if(preOp == '\0' && (str[i] == '+' || str[i] == '-')) { preOp = str[i]; i++; continue; } if(preOp == '+' && (i == str.size() || str[i] == '+' || str[i] == '-')) { if(str1[0] == '-') { str1.erase(str1.begin()); str1 = subStr(str2, str1); } else str1 = addStr(str1, str2); str2 = string(); if(i != str.size()) preOp = str[i]; } else if(preOp == '-' && (i == str.size() || str[i] == '+' || str[i] == '-')) { if(str1[0] == '-') { str1.erase(str1.begin()); str1 = addStr(str2, str1); str1.insert(str1.begin(), '-'); } else str1 = subStr(str1, str2); str2 = string(); if(i != str.size()) preOp = str[i]; } else str2 += str[i]; i++; } cout << str1 << endl; }
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(){ string s; cin >> s; int ans = 0; int len = s.length(); vector<int> num; vector<char> op; if (s[0] <= '9' && s[0] >= '0'){ op.push_back('+'); } for (int i = 0; i < len;){ if (s[i] == '-' || s[i] == '+') op.push_back(s[i++]); else{ int temp = 0; while (s[i] <= '9' && s[i] >= '0'){ temp = temp * 10 + (s[i] - '0'); i++; } num.push_back(temp); } } for (int i = 0; i < op.size(); i++){ if (op[i] == '-') ans -= num[i]; else ans += num[i]; } cout << ans << endl; return 0; }
非常朴素的做法
#include <iostream> #include <string> using namespace std; //只有+,- int main(){ string str; while(cin >> str){ int n = 0; string first = ""; //得到第一个数字,因为可能是十位百位等,所以要逐个获取 while(str[n] != '+' && str[n] != '-'){ first = first + str[n]; ++n; } int sum = atoi(first.c_str()); for(int i = n; i < str.length() - 1; i += 2){ char sig = str[i]; int val = str[i + 1] - '0'; switch(sig){ case '+': sum += val; break; case '-': sum -= val; break; default: break; } } cout << to_string(sum) << endl; } return 0; }
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); int res = 0; int i = 0; int temp = 0; //以数字开头时加一个+,让其以+开头 if (str.charAt(0) >= '0' && str.charAt(0) <= '9') { str = "+" + str; } while (i < str.length()) { //每次进循环时都是以+或-开头 if (str.charAt(i) == '+') { i++; while (i < str.length() && str.charAt(i) != '+' && str.charAt(i) != '-') { int q = str.charAt(i) - '0'; temp = temp * 10 + q; i++; } res += temp; temp = 0; } else { i++; while (i < str.length() && str.charAt(i) != '+' && str.charAt(i) != '-') { int q = str.charAt(i) - '0'; temp = temp * 10 + q; i++; } res -= temp; temp = 0; } } System.out.println(res); } }
#include <bits/stdc++.h> using namespace std; int main(){ string s; cin>>s; stringstream ss(s); int sum=0, x; char c='+'; if(!isdigit(s[0])) ss>>c; while(ss>>x){ if(c=='+') sum += x; else if(c=='-') sum -= x; ss>>c; if(c=='\n') break; } cout<<sum<<endl; return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; //总结目前牛客问题 第一,没有循环输入问题, 第二 有循环输入问题, 第三 输入有多余空格问题 ,第四 中间插入多余空行问题 .... namespace Test0001 { class Program { public static void Main(string[] args) { string line; while (!string.IsNullOrEmpty(line = Console.ReadLine())) Func(line); } public static void Func(string line) { if (string.IsNullOrEmpty(line)) return; //line = Regex.Replace(line, "[{[]", "("); //line = Regex.Replace(line, "[]}]", ")"); line = line.Replace(" ", ""); Console.WriteLine(Calculate(line)); } /// <summary> /// 整数的加减乘除 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Calculate(string str) { int len = str.Length; int il = -1, ir = len; //il : "(" ir :")" for (int i = 0; i < len; i++) { if (str[i] == '(') { il = i; } else if (str[i] == ')') { ir = i; break; } } if (il == -1) //没有括号了 { return MulDiv(str); } else { //str => A+(B)+C string a = str.Substring(0, il); string b = str.Substring(il + 1, ir - il - 1); string c = str.Substring(ir + 1, len - ir - 1); //Console.WriteLine(str.Replace('!', '-')); b = MulDiv(b); if (b[0] == '-') { if (string.IsNullOrEmpty(a) || a.Last() == '-' || a.Last() == '+') b = "0" + b; //避免出现 8 + -5 => 8+0-5 else if (a.Last() == '*' || a.Last() == '/') b = b.Replace('-', '!'); //避免出现 8 * -5 => 8*!5 有与'-'会在后面被分割,所以这里要用!代替,右面反解析!即可 } return Calculate(a + b + c); } } /// <summary> /// 类型转换(反解析) /// </summary> /// <param name="x"></param> /// <returns></returns> public static double DoubleParse(string x) { if (x[0] == '!') x = x.Replace('!', '-'); return double.Parse(x); } /// <summary> /// 乘除运算 /// </summary> /// <returns></returns> public static string MulDiv(string str) { if (str[0] == '-') str = "0" + str; //前面是负号的 补0 int len = str.Length; var oper = str.ToArray().Where(x => x == '+' || x == '-').ToArray(); var nums = str.Split('+', '-'); double[] res = new double[nums.Length]; for (int i = 0; i < nums.Length; i++) { //2 if (nums[i].Length == 1) { res[i] = double.Parse(nums[i]); continue; } //2*3/4*5/6 var operc = nums[i].Where(x => x == '*' || x == '/').ToArray(); var sour = nums[i].Split('*', '/').Select(x => DoubleParse(x)).ToArray(); double sum = sour[0]; int oc = 0, sr = 1; while (oc < operc.Length) { if (operc[oc++] == '*') { sum *= sour[sr++]; } else { sum /= sour[sr++]; } } res[i] = sum; } if (oper.Length > 0) { return AddSub(oper, res); } else { return res[0].ToString(); } } /// <summary> /// 加减运算 /// </summary> /// <returns></returns> public static string AddSub(char[] opr, double[] res) { double sum = res[0]; int or = 0, rs = 1; while (or < opr.Length) { if (opr[or++] == '+') { sum += res[rs++]; } else { sum -= res[rs++]; } } return sum.ToString(); } } }
package main import ( "fmt" "strconv" "strings" ) func main(){ var str string fmt.Scanln(&str) arr := strings.Split(str, "") sum:=0 if arr[0]=="-"{ sum=0 for i:=0;i<len(arr) ;i=i+2 { if arr[i]=="-" { b,_ := strconv.Atoi(arr[i+1]) sum=sum-b; }else{ b,_ := strconv.Atoi(arr[i+1]) sum=sum+b; } } }else{ num,_:=strconv.Atoi(arr[0]) sum=num for i:=1;i<len(arr) ;i=i+2 { if arr[i]=="-" { b,_ := strconv.Atoi(arr[i+1]) sum=sum+b; }else{ b,_ := strconv.Atoi(arr[i+1]) sum=sum+b; } } } s := strconv.Itoa(sum) fmt.Println(s) }
#include <bits/stdc++.h> using namespace std; int main(){ int ans=0,i=0,start=0,end=0; bool plus=true; string str; cin>>str; if(str[0]=='-'){ end++; start++; plus=false; } while(i<=str.size()){ if(str[i]=='-'||str[i]=='+'||i==str.size()) end=i; if(end>start){ int num=stoi(str.substr(start,end-start)); if(start>=1) plus = str[start-1]=='+'; ans= plus==true ? ans+num:ans-num; start=end+1; } i++; } cout<<ans; return 0; }
string = input() n = len(string) i, total = 0, 0 while i < n: if string[i] == "+": i += 1 tmp = "" while i < n and string[i].isdigit(): tmp += string[i] i += 1 total += int(tmp) elif string[i] == "-": i += 1 tmp = "" while i < n and string[i].isdigit(): tmp += string[i] i += 1 total -= int(tmp) else: tmp = "" while i < n and string[i].isdigit(): tmp += string[i] i += 1 total += int(tmp) print(str(total))
/* 推荐楼上Jack的。 才知道带+-也能直接parseInt。 */ import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); boolean flag = true; int len = s.length(); int ans = 0; int beg = 0; //阶段开始位置。 for (int i = 0; i < len; i++) { if (s.charAt(i) == '+' || s.charAt(i) == '-') { String tmp = s.substring(beg, i); if (tmp != null && !tmp.trim().isEmpty()) { int num = Integer.parseInt(tmp); if (flag) { ans += num; } else { ans -= num; } } beg = i + 1; if (s.charAt(i) == '+') { flag = true; } else { flag = false; } } } int num = Integer.parseInt(s.substring(beg, len)); if (flag) { ans += num; } else { ans -= num; } System.out.println(ans); } }
}
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void async function () { var inp=(await readline()) console.log(eval(inp)) }()
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s=in.next(); s=s.replaceAll("-","+-"); int sum=0; String si=""; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='+'){ if(si.equals("")) continue; sum+=Integer.parseInt(si); si=""; }else{ si+=s.substring(i,i+1); } } sum+=Integer.parseInt(si); System.out.printf("%d",sum); } }
s = input() sign = 1 # sign记录当前符号 res, num = 0, 0 # num保存当前数值 for i in s: if i.isdigit(): # 输入为数字时,更新num num = 10*num + int(i) else: # 输入不为数字时,先计算上一步运算 res += sign*num num = 0 # num归0,更新符号 if i == '+': sign = 1 elif i == '-': sign = -1 res += sign*num # 补上最后一步运算 print(res)