当前位置:网站首页>leetcode-aboutString
leetcode-aboutString
2022-07-26 05:36:00 【CodeStars码星人】
关于字符串运算

最经典的肯定为这道题:字符串相加
思路:一开始看到题目要求,不能把输入的字符串直接转化为数字。然后就想,既然不让我用,那我就自己写一个。
public int stringToInt(String num1) {
int total=0;
int length=num1.length();
for(int i=0;i<length;i++){
total+=(num1.charAt(i)-'0')*Math.pow(10,length-i-1);
}
return total;
}
于是就写了一个string转int的函数,打算把两个数转化为int执行相加操作。然后得到加数的int。
此时要把int转化为String,想了好久不知道该怎么转,后来看了答案,发现可以:
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("");
stringBuffer.append(addnum);
建立一个stringBuffer,append(“”),然后可以append(int)
就可以输出了。
原本以为已经天衣无缝了,但是却出现了一个问题,就是这种情况会发生溢出!!!
如果两个数很大很大,比如下面这种情况:
那么两个int相加实际上已经超出了int所能表示的范围了,所以就会溢出,此时的int并不是真实两个数相加的结果,而我们将int转化的string肯定也不是真实的结果。
所以这种方案是不可行的
为了结果不溢出,我们不能将其转化为int相加,而得利用字符串,每一位每一位相加,这样(字符串)没有溢出的情况。
StringBuffer result=new StringBuffer();
result.append("");
int tag1=num1.length()-1;
int tag2=num2.length()-1;
int tagResult1=0;
int tagResult2=0;
int sum=0;
int carry=0;
while(tag1>=0||tag2>=0){
if(tag1<0){
tagResult1='0';
}else{
tagResult1=num1.charAt(tag1);
}
if(tag2<0){
tagResult2='0';
}else{
tagResult2=num2.charAt(tag2);
}
sum=tagResult1-'0'+tagResult2-'0'+carry;
result.append(sum%10);
//直接将carry看成sum/10 就不用去判断是否大于10,需不需要进位,carry已经可以表明了
carry=sum/10;
tag1--;
tag2--;
//999+1 这种刚好000然后进一位的情况
if(tag1<0&&tag2<0&&carry==1){
result.append(1);
}
}
return result.reverse().toString();
这代码写出来又臭又长,简化一下:
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
字符串相乘
思路:
leetcode大佬思路:
代码:
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
//Multiply Strings 同样不能直接转化为int相乘,因为数据太大的话,结果会溢出
//所以仍然要用字符串相加的思路
//字符串123 *456 实际上就是 6*123+50*123+400*123 (这里的加法就用我们已经写出来的字符串加法)
//而6*123 这种乘法,也不难,也是加法的思路,依次乘,然后进位
String res=new String();
for(int i = num1.length() - 1 ; i >= 0; i--){
int mul = (num1.charAt(i) - '0');
StringBuffer str=new StringBuffer();
int sum = 0,add = 0;
for(int j = num2.length() - 1;j >= 0; j--){
sum=mul*(num2.charAt(j)-'0')+add;
str.append(sum%10);
add=sum/10;
//!!!!!
//这里也要注意 ! 相乘也会有溢出的情况!!!
if(j == 0 && add != 0){
str.append(add % 10);
}
}
str.reverse();
for(int k=i;k < num1.length() - 1; k++){
str.append(0);
}
res=addStrings(res,str.toString());
}
return res;
}
public String addStrings(String num1, String num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
}
}
另附上大神的解法:

class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int[] res = new int[num1.length() + num2.length()];
for (int i = num1.length() - 1; i >= 0; i--) {
int n1 = num1.charAt(i) - '0';
for (int j = num2.length() - 1; j >= 0; j--) {
int n2 = num2.charAt(j) - '0';
int sum = (res[i + j + 1] + n1 * n2);
res[i + j + 1] = sum % 10;
res[i + j] += sum / 10;
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < res.length; i++) {
if (i == 0 && res[i] == 0) continue;
result.append(res[i]);
}
return result.toString();
}
}
作者:breezean
链接:https://leetcode.cn/problems/multiply-strings/solution/you-hua-ban-shu-shi-da-bai-994-by-breezean/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
- OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation
- Use playbook in ansible
- Mongodb common commands
- 数仓搭建-DIM层
- 学生如何申请免费IDEA
- 高分子物理试题库
- kubernetes install completed
- MongonDB API使用
- Hack the box - Introduction to networking module detailed Chinese tutorial
猜你喜欢

CANoe-XML在Test Modules中的应用

Hack The Box - Web Requests Module详细讲解中文教程

Redis持久化-AOF

C language - Advanced pointer

FTP实验及概述

Development to testing: a six-year road to automation from scratch

DOM operation -- operation node

动态内存管理及柔性数组

Debugging sharp weapon! A lightweight log library log.c

MBA-day29 算术-绝对值初步认识
随机推荐
How to name the project version number? Looks like cow b
520 for what? DIY is a high-value RGB clock that girls want to watch
我又发现了超赞的软硬件项目,全部开源
三本毕业,三年嵌入式软件的心路历程
MongoDB 常用命令
TZC 1283: simple sort - select sort
YOLOV3预备工作
Redis事务
Lightweight MCU command line interaction project, all open source
How students apply for free idea
开发项目事半功倍,一款开源的stm32驱动库大集合
SSH Remote Management
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
FPGA question brushing sequence detection
If MySQL calculates the current month change / current month increase / year-on-year change / year-on-year increase?
代码审计之百家cms
Knowledge points of Polymer Physics
Development to testing: a six-year road to automation from scratch
Chinese character style transfer --- learn the conversion and generation of one to many programmed Chinese characters through generation confrontation network
Another open source artifact, worth collecting and learning!
