POJ-1503 Integer Inquiry
2015-07-21 10:40
483 查看
#include <iostream> #include <string> using namespace std; string add(string str1, string str2) { string str; int len1 = str1.length(); int len2 = str2.length(); if(len1 < len2) { for(int i = 1; i <= len2 - len1; i++) str1 = "0" + str1; } else { for(int i = 1; i <= len1 - len2; i++) str2 = "0" + str2; } len1 = str1.length(); int temp,a,b = 0; for(int i = len1 - 1; i >= 0; i--) { temp = str1[i] - '0' + str2[i] - '0' + b; a = temp % 10; b = temp / 10; str = char(a+'0') + str; } if (b != 0) str = char(b + '0') + str; return str; } int main() { string str1; string sum = "0"; while(cin >> str1) { if(str1 == "0") break; else sum = add(sum,str1); } cout << sum <<endl; return 0; }
</pre><pre name="code" class="cpp">题意:求大数和。大数 自然不能用普通加减。
</pre><pre name="code" class="cpp">解题:参考网上博客。
1. 构造自定义函数add。
2. int len1 = str1.length() 是计算出str1里面数字的个数。之后与len2作对比 进行前面补0 使长度相同 (注意补0时 是字符串加减 “0”双引号)。
3. 长度相同后 从末尾开始加减。(注意 进位b赋初值0,temp+b)每一位的计算存入新的string str。(char(a+'0') char进行强制转换 不然就是整形)。
相关文章推荐
- 探秘Java中String、StringBuilder以及StringBuffer
- 转载priority_queue用法总结
- iOS编程第四版第10章 UINavigationController
- HDU 3530 Subsequence(单调队列维护)
- ios-画图UIBezierPath
- [iOS]获取iOS UI框架中最上层的UIViewController对象
- iOS UILabel自适应高度的简单实现
- git SSL certificate problem: unable to get local issuer certificate
- SpannableString与SpannableStringBuilder
- Cocoa深入学习:NSOperationQueue、NSRunLoop和线程安全
- Flask 中 @app.before_request、@app.after_request 和 @app.teardown_request
- Hive query issue
- Flex Viewer解析
- 解决Maven更新后错误Dynamic Web Module 3.0 requires Java 1.6 or newer
- HTML学习笔记——frameset和marquee
- JSP JSTL EL 删除空行 <%@ page trimDirectiveWhitespaces="true" %>
- Qt5官方demo分析集29——Extending QML - Property Value Source Example
- [Leetcode 52, Hard] N Queens II
- UISegmentedControl的使用 IOS学习手记
- JAVA基础-GUI