请设计一个算法能够完成两个用字符串存储的整数进行相加操作,对非法的输入则返回 error
数据范围:字符串长度满足
Java做的很累啊。尾部相加,进位保留往前加,加到没有进位为之。 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String a = scanner.next(); String b = scanner.next(); if (!legal(a) || !legal(b)) { System.out.println("error"); }else { System.out.println(add(a, b)); } } public static String add(String a,String b) { int i = a.length() - 1; int j = b.length() - 1; int go = 0; String res = ""; while (i >= 0 && j >= 0) { int a1 = Integer.parseInt(a.substring(i, i + 1)); int b1 = Integer.parseInt(b.substring(j, j + 1)); int sum = a1 + b1 + go; if (sum >= 10) { go = 1; sum = sum - 10; }else { go = 0; } res = sum + res; i --; j --; } String rem = i > j ? a.substring(0, i - j) : b.substring(0, j - i); if (go == 0) { res = rem + res; } int cur = rem.length() - 1; while (cur >= 0) { int num = Integer.parseInt(rem.substring(cur, cur + 1)); int sum = num + go; if (sum >= 10) { sum = sum - 10; go = 1; } else { go = 0; break; } res = String.valueOf(sum) + res; cur --; } if (go == 1) { res = "1" + res; } return res; } public static boolean legal(String s) { for (int i = 0;i < s.length();i ++) { if ('0' <= s.charAt(i) && s.charAt(i) <= '9') { continue; }else return false; } return true; } }
//注意int、long均不能满足需求 import java.util.Scanner; import java.math.BigInteger; public class Main{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); try{ BigInteger n = scanner.nextBigInteger (); BigInteger m = scanner.nextBigInteger (); System.out.println(m.add(n)); }catch(Exception e) { System.out.println("error"); } } }
题目要求手撕大整数算法 那些直接调用的也是够了。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
using namespace std;
//常量区
typedef long long ll;
bool is_num(string a){
for(int i = 0; i < a.length(); i++)
if(a[i] > '9' || a[i] < '0') return false;
return true;
}
//函数区
void MyAdd(string a, string b){
if(!is_num(a) || !is_num(b)) {printf("error\n"); return; }
int max_len = max(a.length(), b.length());
string c = "";
for(int i = 0; i < max_len; i++) c += '0';
int al = a.length();
int bl = b.length();
if(al < bl)
for(int i = 0; i < bl - al; i++) a = '0' + a;
else if(al > bl)
for(int i= 0; i < al - bl; i++) b = '0' + b;
for(int i = max_len - 1; i >= 0; i--){
int tmp = int(a[i]) + int(b[i]) + int(c[i]) - 48*3;
if(tmp < 10) c[i] = tmp + '0';
if(tmp >= 10) {
c[i] = tmp % 10 + '0';
char ss = (tmp / 10 + '0');
if(i == 0) c = ss + c;
else c[i-1] = ss;
}
}
cout<<c<<endl;
}
//main函数
int main(){
string a, b;
while(cin>>a>>b){
MyAdd(a, b);
}
return 0;
}
/*
123 123
abd 123
*/
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String s = scan.nextLine(); String[] ss = s.split(" "); String result = add(ss[0], ss[1]); System.out.println(result); } } public static String add(String s1, String s2) { char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); if (!checkValid(c1) || !checkValid(c2)) { return "error"; } if (c1.length < c2.length) { char[] tmp = c1; c1 = c2; c2 = tmp; } int cf = 0; int i = c1.length - 1, j = c2.length - 1; while (j >= 0) { int tmp = c1[i] - '0' + c2[j] - '0' + cf; cf = tmp / 10; c1[i] = (char) (tmp % 10 + '0'); i--; j--; } while (i >= 0 && cf > 0) { int tmp = c1[i] - '0' + cf; cf = tmp / 10; c1[i] = (char) (tmp % 10 + '0'); i--; } StringBuilder sb = new StringBuilder(); if (cf > 0) { sb.append('1'); } for (int k = 0; k < c1.length; k++) { sb.append(c1[k]); } return sb.toString(); } public static boolean checkValid(char[] c) { for (int i = 0; i < c.length; i++) { if (c[i] < '0' || c[i] > '9') { return false; } } return true; } }
#include<iostream> #include<string> #include<algorithm> using namespace std; int main() { string stra; string strb; while(cin >> stra >> strb) { bool flag = false; for(int i = 0; i < stra.size(); i++) { if(!(stra[i] >= '0' && stra[i] <= '9')) { cout << "error" << endl; flag = true; break; } } if(flag) break; for(int i = 0; i < strb.size(); i++) { if(!(strb[i] >= '0' && strb[i] <= '9')) { cout << "error" << endl; flag = true; break; } } if(flag) break; string ret; int carry = 0; int i = stra.size() - 1; int j = strb.size() - 1; while(i >= 0 && j >= 0) { int sum = (stra[i] - '0') + (strb[j] - '0') + carry; carry = sum / 10;//计算carry和sum不能调换顺序 sum = sum % 10; ret = ret + to_string(sum); i--; j--; } while(i >= 0) { int sum = (stra[i] - '0') + carry; carry = sum / 10; sum = sum % 10; ret = ret + to_string(sum); i--; } while(j >= 0) { int sum = (strb[j] - '0') + carry; carry = sum / 10; sum = sum % 10; ret = ret + to_string(sum); j--; } if(carry) ret = ret + '1'; reverse(ret.begin(), ret.end()); cout << ret << endl; } }
package 算法题.美团点评; import java.math.BigInteger; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IntAdd { public static void main(String args[]) { Scanner input = new Scanner(System.in); // 方法一 // try{ // BigInteger n = input.nextBigInteger(); // BigInteger m = input.nextBigInteger(); // System.out.println(n.add(m)); // }catch (Exception e) { // System.out.println("error"); // } String n = input.next(); String m = input.next(); String sum = resolute(n, m); System.out.println(sum); } public static String resolute(String n, String m) { final String ERROR = "error"; // 判断字符串是否符合标准 if (n == null || m == null) return ERROR; if (!isNumber(n) || !isNumber(m)) { return ERROR; } // n、m的正负值 boolean boolN = isRightNum(n); boolean boolM = isRightNum(m); if (n.charAt(0) == '+' || n.charAt(0) == '-') n = n.substring(1); if (m.charAt(0) == '+' || m.charAt(0) == '-') m = m.substring(1); if (boolN && boolM) { // 同为正值 return toSum(n, m); } else if (!boolN && !boolM) { // 同为负值 return '-' + toSum(n, m); } else { // 预处理,n为正数,m为负数,做和。要注意借位。 if (boolN) { return toSub(n, m); } else { return toSub(m, n); } } } /** * 判断一个字符串是否是数字。"-123"、"+123","0123"都是数字 * * @param s * 待判断的字符串 * @return */ public static boolean isNumber(String s) { final String REGEX = "[-+\\d]\\d*"; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(s); if (!matcher.matches()) return false; return true; } /** * 判断一个字符串是否是正整数 * * @param s * @return */ public static boolean isRightNum(String s) { final String REGEX = "-\\d+"; Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(s); if (matcher.matches()) return false; return true; } /** * 消除前导0, 0000123输出 123 * * @param s * @return */ public static String ignore0(String s) { int i; for (i = 0; i < s.length(); i++) { if (s.charAt(i) != '0') break; } return s.substring(i); } /** * 两个正数相加 * * @param n * @param m * @return */ public static String toSum(String n, String m) { // System.out.println("调用了tosum():"+n+" "+m); StringBuffer str = new StringBuffer(); int tem = 0; // 存储进位 int i = n.length() - 1, j = m.length() - 1; // 两个正数相加、或两个负数相加 for (; j >= 0 && i >= 0; i--, j--) { tem = tem + n.charAt(i) - '0' + m.charAt(j) - '0'; str.append(tem % 10); tem /= 10; } // 处理多出来的位 while (i >= 0) { tem = tem + n.charAt(i) - '0'; str.append(tem % 10); tem /= 10; i--; } while (j >= 0) { tem = tem + m.charAt(j) - '0'; str.append(tem % 10); tem /= 10; j--; } str.append(tem); str = str.reverse(); return ignore0(str.toString()); } /** * 字符串做差 n-m 预处理 * * @param n * @param m * @return */ public static String toSub(String n, String m) { if (n.length() > m.length()) { return doSub(n, m); } else if (n.length() < m.length()) { return '-' + doSub(m, n); } else { if (n.compareTo(m) >= 0) { return doSub(n, m); } else { return '-' + doSub(m, n); } } } /** * 做差n-m * * @param n * @param m * @return */ public static String doSub(String n, String m) { StringBuffer str = new StringBuffer(); int tem = 0; int i = n.length() - 1, j = m.length() - 1; for (; i >= 0 && j >= 0; i--, j--) { tem = n.charAt(i) - tem - m.charAt(j); if (tem<0) { tem = tem + 10; str.append(tem); tem = 1; } else { str.append(tem); tem = 0; } } while (i >= 0) { tem = n.charAt(i) - '0' - tem; if (tem < 0) { str.append(tem + 10); tem = 1; } else { str.append(tem); tem = 0; } i--; } str = str.reverse(); String s = ignore0(str.toString()); if(s == null || s.isEmpty()) s = "0"; return s; } }
//本题如 @是个Offer就行 同学说的一样,int long都不能满足。 //思路:借助栈,先进后出的原则,从低位开始相加,依次存到栈中 //特别注意相加的进位flag,初始为0 //经 @Striver_zhoudw 同学和 @至心 同学 的提醒,已对长度不一致的情况做了修改,再次感谢 #include <iostream> #include <string> #include <stack> using namespace std; int isalldi(string str) { for (int i = 0; i < str.size(); i++) { if (!isdigit(str[i])) //判断是否有非数字的元素 { cout<<"error"<<endl; return 0; } } return 1; } int main() { string str1,str2; while(cin>>str1>>str2) { int sum=0; stack<int>si; int flag=0; if(isalldi(str1)&&isalldi(str2))//str1 str2 都是数字 { if (str1.size()<str2.size()) //保证str1是较长的字符串 { swap(str1,str2); } while (m>=0) //较短的字符串长度来控制加法的次数 { sum=(str1[n--]-'0')+(str2[m--]-'0')+flag; flag=sum/10; si.push(sum%10); } int n=str1.size()-1; int m=str2.size()-1; int len=n-m; //两个字符串的长度差 while (len-->0) //如果长度不一致,需要把较长的字符串再与进位相加 { sum=flag+(str1[len]-'0'); flag=sum/10; si.push(sum%10); } if (flag)//注意如果加完之后进位=1,仍需要再入栈的 { si.push(flag); } while(!si.empty())//栈非空 { cout<<si.top();//弹出顶层元素 si.pop(); } cout<<endl; } } return 0; }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String str1 = in.next(); String str2 = in.next(); System.out.println(caculate(str1,str2)); } } public static String caculate(String s1,String s2){ int i = s1.length() - 1,j = s2.length() - 1; int carry = 0; StringBuilder sb = new StringBuilder(); while(i >= 0 || j >= 0 || carry != 0){ if(i >= 0 && !Character.isDigit(s1.charAt(i)) || j >= 0 && !Character.isDigit(s2.charAt(j))) return "error"; int m = i < 0 ? 0 : s1.charAt(i) - '0'; int n = j < 0 ? 0 : s2.charAt(j) - '0'; int sum = m + n + carry; sb.append(sum % 10); carry = sum / 10; i --; j --; } return sb.reverse().toString(); } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] strNum = br.readLine().trim().split(" "); System.out.println(add(strNum[0].toCharArray(), strNum[1].toCharArray())); } private static String add(char[] num1, char[] num2) { StringBuilder sb = new StringBuilder(); int len1 = num1.length, len2 = num2.length; if(len1 < len2){ char[] temp = num1; num1 = num2; num2 = temp; } int carry = 0; int i = num1.length - 1, j = num2.length - 1; while(i >= 0 && j >= 0){ if(num1[i] > 57 || num1[i] < 48 || num2[j] > 57 || num2[j] < 48) return "error"; int num = (num1[i] - '0') + (num2[j] - '0') + carry; carry = num / 10; sb.append(num % 10); i --; j --; } while(i >= 0){ if(num1[i] > 57 || num1[i] < 48) return "error"; int num = (num1[i] - '0') + carry; carry = num / 10; sb.append(num % 10); i --; } if(carry > 0) sb.append(carry); return sb.reverse().toString(); } }2.偷懒法:直接转成数字相加,遇到异常就打印error
try: num1, num2 = map(int, input().split()) print(num1 + num2) except: print("error")
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str1=sc.next(); String str2=sc.next(); int len1=str1.length(); int len2=str2.length(); String result=""; Stack<Integer> stack1=new Stack<>(); Stack<Integer> stack2=new Stack<>(); Stack<Integer> stack3=new Stack<>(); //让两个栈对齐 if(len1>len2) { int count=len1-len2; while(count-->0) stack2.push(0); } else if(len1<len2) { int count=len2-len1; while(count-->0) stack1.push(0); } //分别入栈 for(int i=0;i<str1.length();i++) { char ch=str1.charAt(i); if(ch<'0'||ch>'9') { System.out.println("error"); return; } stack1.push(ch-'0'); } for(int i=0;i<str2.length();i++) { char ch=str2.charAt(i); if(ch<'0'||ch>'9') { System.out.println("error"); return; } stack2.push(ch-'0'); } //相加入新栈 int num1,num2,num3,add=0; while( !stack1.isEmpty() && !stack2.isEmpty() ) { num1=stack1.pop(); num2=stack2.pop(); num3=num1+num2+add; add=num3/10; num3%=10; stack3.push(num3); } //处理最后的进位 if(add==1) stack3.push(1); while(!stack3.isEmpty()) result+=stack3.pop(); System.out.println(result); } }
/* 总体思路就是把两个字符串倒序的分别放到两个整型数组中, 然后从第一位开始进行对应相加,大于10的进一位,最后输出的时候倒序输出就行 细节描述在代码注释中 */import java.util.*;
}
#include <iostream> #include <string> using namespace std; bool isNum(string str) { for(int i = 0; i < str.size(); i++) if(str[i] <= '0' || str[i] >= '9') return false; return true; } void pinjie(string str1, string str2) { int i1 = str1.size() - 1; int i2 = str2.size() - 1; string str = ""; int c = 0;//进位位 while(1) { int n; if(i1 >= 0 && i2 >= 0) n = str1[i1] + str2[i2] - '0' - '0' + c; else if(i1 >= 0 && i2 < 0) n = str1[i1] - '0' + c; else if(i2 >= 0 && i1 < 0) n = str2[i2] - '0' + c; else break; if(n > 10) { c = 1; n %= 10; } else c = 0; str = (char)(n + '0') + str; i1--; i2--; } if(c)str = "1" + str; cout << str << endl; } int main() { string str1,str2; cin >> str1 >> str2; if(isNum(str1) && isNum(str2)) pinjie(str1, str2); else cout << "error" << endl; return 0; }
<?php //大数相加 function bigAdd($s1,$s2){ $len1 = strlen($s1); $len2 = strlen($s2); $j = 0;//进位标识符 $re = ''; for($inx1 = $len1-1,$inx2 = $len2-1;($inx1>=0||$inx2>=0);--$inx1,--$inx2){ $item1 = ($inx1>=0) ? (int)$s1[$inx1]:0; $item2 = ($inx2>=0) ? (int)$s2[$inx2]:0; $sum = $item1 + $item2 + $j; if($sum>9){ $j=1; $sum-=10; }else $j=0; $re = (string)$sum.$re; } if($j>0) $re = (string)$j.$re; return $re; } $arr = explode(" ",trim(fgets(STDIN))); $s1 = $arr[0]; $s2 = $arr[1]; if(!is_numeric($s1)||!is_numeric($s2)) echo 'error'; else echo bigAdd($s1,$s2);
//直接写大数类,先反向,然后ab补齐,运算,再反向,over #include<iostream> #include<algorithm> using namespace std; class BigNumber{ string s; public: BigNumber(string s){ for(int i=0;i<s.size();++i) { if(s[i]<'0'||s[i]>'9') throw "Error"; this->s=s; } } BigNumber operator + (BigNumber other) { string a=other.s; string b=s; reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); int mx=max(a.size(),b.size()); while(a.size()<mx) a+='0'; while(b.size()<mx) b+='0'; BigNumber ans(""); while(ans.s.size()<=mx) ans.s+='0'; for(int i=0;i<mx;++i) { ans.s[i]+=a[i]-'0'; ans.s[i]+=b[i]-'0'; if(ans.s[i]>'9') { ans.s[i]-=10; ans.s[i+1]++; } } if(ans.s[mx]=='0') ans.s.erase(ans.s.end()-1); reverse(ans.s.begin(),ans.s.end()); return ans; } friend ostream& operator <<(ostream& o,const BigNumber& n) { o<<n.s; return o; } }; int main() { string a,b; while(cin>>a>>b) { try{ BigNumber A(a); BigNumber B(b); cout<<(A+B)<<endl; }catch(...) { cout<<"error"<<endl; } } return 0; }
#include<iostream>
#include<string>
using namespace std;
bool is_number(string s)
{
for (int i = 0; i < s.length(); i++)
{
if (s[i] < '0' || s[i] > '9') return false;
}
return true;
}
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
int i, carry, flag = 0, digit = s1.length() > s2.length() ? s1.length() : s2.length();
string ex1, ex2, num1, num2;
int *sum = new int[digit + 1]{ 0 };
for (i = 0; i < digit - s1.length(); i++) ex1 += "0";
for (i = 0; i < digit - s2.length(); i++) ex2 += "0";
num1 = ex1 + s1;
num2 = ex2 + s2;
if (is_number(num1) && is_number(num2))
{
flag = 1;
for (i = digit - 1; i >= 0; i--)
{
sum[i + 1] = (num1[i] - '0') + (num2[i] - '0');
}
}
for (i = digit ; i > 0; i--)
{
if (sum[i] >= 10)
{
carry = sum[i] / 10;
sum[i] %= 10;
sum[i - 1] += carry;
}
}
if (flag == 0) cout << "error";
else
{
if (sum[0] == 0) for (i = 1; i <= digit; i++) cout << sum[i];
else for (i = 0; i <= digit; i++) cout << sum[i];
}
cout << endl;
}
system("pause");
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
bool is_legal(string str)
{
for (int i = 0; i < str.length(); ++i)
{
if (!isdigit(str[i]))
{
return false;
}
}
return true;
}
string add_string(string str1, string str2)
{
string res = "";
int flag = 0, value = 0, sum = 0;
vector<int> res_tmp;
if (str1.size()<str2.size()) // 保证str1的长度最长
{
swap(str1, str2);
}
for (int i = str2.size() - 1; i >= 0; --i) // 相同位 从低位开始相加
{
sum = (str1[i] - '0') + (str2[i] - '0') + flag;
value = sum % 10;
flag = sum / 10;
res_tmp.push_back(value);
}
for (int i = str2.size(); i < str1.size(); ++i) // 将str1多余的位数和进位相加
{
sum = (str1[i] - '0') + flag;
value = sum % 10;
flag = sum / 10;
res_tmp.push_back(value);
}
if (flag == 1)
{
res_tmp.push_back(flag);
}
for (int i = res_tmp.size() - 1; i >= 0; --i)
{
string tmp = to_string(res_tmp[i]);
res += tmp;
}
return res;
}
int main()
{
string str_input;
while (getline(cin, str_input))
{
if (!str_input.empty())
{
string str_tmp1 = "";
string str_tmp2 = "";
int position = str_input.find(' ');
str_tmp1 = str_input.substr(0, position);
str_tmp2 = str_input.substr(position + 1, str_input.length() - position);
if (is_legal(str_tmp1) && is_legal(str_tmp2))
{
cout << add_string(str_tmp1, str_tmp2) << endl;
}
else
{
cout << "error" << endl;
}
}
}
return 0;
}
#include <iostream> #include <string> using namespace std; string add(string a, string b) { int i = a.size(), j = b.size(); int c = 0; string ans = ""; while (i || j || c) { if ((i > 0 && !isdigit(a[i - 1])) || (j > 0 && !isdigit(b[j - 1]))) return "error"; int x = i > 0 ? a[--i] - '0' : 0; int y = j > 0 ? b[--j] - '0' : 0; int tmp = x + y + c; if (tmp >= 10) { tmp %= 10; c = 1; } else c = 0; ans = to_string(tmp) + ans; } return ans; } int main() { string strA, strB; while (cin>>strA>>strB) cout<<add(strA, strB)<<endl; return 0; }