当前位置:网站首页>leetcode-aboutString
leetcode-aboutString
2022-07-26 05:39:00 【Codestars codestars】
About string operations

The most classic must be this problem : String addition
Ideas : At first, I saw the requirements of the topic , You cannot convert the input string directly into numbers . Then I thought , Since I'm not allowed to use it , Then I'll write one myself .
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;
}
So I wrote a string turn int Function of , I intend to convert two numbers into int Perform the add operation . Then we get the addend int.
At this point, you should int Turn into String, After thinking for a long time, I don't know how to turn , Then I read the answer , Discovery can :
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("");
stringBuffer.append(addnum);
Build a stringBuffer,append(“”), Then you can append(int)
You can output .
I thought it was perfect , But there is a problem , This is the case where overflow occurs !!!
If two numbers are very big , For example, the following situation :
Well, the two one. int The sum has actually exceeded int What can be expressed , So it will overflow , At this time int It is not the result of adding two real numbers , And we will int Transformed string Certainly not the real result .
So this plan is not feasible
In order not to overflow the results , We cannot turn it into int Add up , You have to use strings , Every bit adds up , such ( character string ) There is no overflow .
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);
// Direct will carry as sum/10 There is no need to judge whether it is greater than 10, Do you need to carry ,carry It can already be shown
carry=sum/10;
tag1--;
tag2--;
//999+1 This is just right 000 Then enter a situation
if(tag1<0&&tag2<0&&carry==1){
result.append(1);
}
}
return result.reverse().toString();
This code is smelly and long , To simplify the :
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();
String multiplication
Ideas :
leetcode Big guy thinking :
Code :
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
//Multiply Strings Similarly, it cannot be directly transformed into int Multiply , Because the data is too large , The result will overflow
// So we still need to use the idea of string addition
// character string 123 *456 It's actually 6*123+50*123+400*123 ( The addition here uses the string addition we have written )
// and 6*123 This multiplication , It's not difficult. , It is also the idea of addition , Multiply sequentially , And then carry
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;
//!!!!!
// Here, too ! Multiplication also has overflow !!!
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();
}
}
Also attached is the solution of the great God :

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();
}
}
author :breezean
link :https://leetcode.cn/problems/multiply-strings/solution/you-hua-ban-shu-shi-da-bai-994-by-breezean/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
- Hack The Box - Web Requests Module详细讲解中文教程
- 电机控制专栏文章汇总
- MongonDB API使用
- OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation
- Hack The Box - Introduction to Networking Module详细讲解中文教程
- Hack the box - Web requests module detailed Chinese tutorial
- 高效,可靠,安全的串口通讯开源方案
- 嵌入式通用学习路线整理
- You'd better not take this kind of project!
- [STM32 series summary] blogger's way to quickly advance STM32 in actual combat (continuous update)
猜你喜欢

Recommended reading: how can testers get familiar with new businesses quickly?

QT writing IOT management platform 47 general database settings

TZC 1283: simple sort Bubble Sort

Mongondb API usage
C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises

MongoDB 常用命令

DOM操作--操作节点

NetCore MySql The user specified as a definer (‘admin‘@‘%‘) does not exist

How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects

520送什么?DIY一个高颜值RGB时钟,女生看了都想要
随机推荐
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
Use of feign (Part 2)
It's enough for newcomers to learn how to do functional tests
Hack the box - Introduction to networking module detailed Chinese tutorial
No EGL display error resolution
选电子工程被劝退,真的没前景了?
MongonDB API使用
动态内存管理及柔性数组
Thread三种实现方式 和 Handler的用法
Recommended reading: how can testers get familiar with new businesses quickly?
How to name the project version number? Looks like cow b
Basic methods of realizing licensing function in C language
Mba-day29 arithmetic - preliminary understanding of absolute value
Home VR panoramic display production to improve customer transformation
How are masters refined?
Dynamic memory management and flexible array
Polymer physics test question bank
电机控制专栏文章汇总
Redis发布订阅
Embedded development notes, practical knowledge sharing
