@@ -74,19 +74,13 @@ targetWord 的数值为 "aaaa" -> "0000" -> 0
74
74
``` python
75
75
class Solution :
76
76
def isSumEqual (self , firstWord : str , secondWord : str , targetWord : str ) -> bool :
77
- n = 9
78
- firstWord = ' a' * (n - len (firstWord)) + firstWord
79
- secondWord = ' a' * (n - len (secondWord)) + secondWord
80
- targetWord = ' a' * (n - len (targetWord)) + targetWord
81
- carry = 0
82
- while n > 0 :
83
- n -= 1
84
- i = ord (firstWord[n]) - ord (' a' )
85
- j = ord (secondWord[n]) - ord (' a' )
86
- carry, s = divmod (i + j + carry, 10 )
87
- if targetWord[n] != chr (ord (' a' ) + s):
88
- return False
89
- return True
77
+ def transfer (word ):
78
+ res = 0
79
+ for c in word:
80
+ res *= 10
81
+ res += (ord (c) - ord (' a' ))
82
+ return res
83
+ return transfer(firstWord) + transfer(secondWord) == transfer(targetWord)
90
84
```
91
85
92
86
### ** Java**
@@ -96,34 +90,40 @@ class Solution:
96
90
``` java
97
91
class Solution {
98
92
public boolean isSumEqual (String firstWord , String secondWord , String targetWord ) {
99
- int n = 9 ;
100
- firstWord = fillA(firstWord, n);
101
- secondWord = fillA(secondWord, n);
102
- targetWord = fillA(targetWord, n);
103
- int carry = 0 ;
104
- while (-- n >= 0 ) {
105
- int i = firstWord. charAt(n) - ' a' ;
106
- int j = secondWord. charAt(n) - ' a' ;
107
- int s = i + j + carry;
108
- if (targetWord. charAt(n) != (char ) (' a' + (s % 10 ))) {
109
- return false ;
110
- }
111
- carry = s / 10 ;
112
- }
113
- return true ;
93
+ return transfer(firstWord) + transfer(secondWord) == transfer(targetWord);
114
94
}
115
95
116
- private String fillA (String word , int n ) {
117
- StringBuilder sb = new StringBuilder ();
118
- for (int i = 0 ; i < n - word. length(); ++ i) {
119
- sb. append(" a" );
96
+ private int transfer (String word ) {
97
+ int res = 0 ;
98
+ for (char c : word. toCharArray()) {
99
+ res *= 10 ;
100
+ res += (c - ' a' );
120
101
}
121
- sb. append(word);
122
- return sb. toString();
102
+ return res;
123
103
}
124
104
}
125
105
```
126
106
107
+ ### ** C++**
108
+
109
+ ``` cpp
110
+ class Solution {
111
+ public:
112
+ bool isSumEqual(string firstWord, string secondWord, string targetWord) {
113
+ return transfer(firstWord) + transfer(secondWord) == transfer(targetWord);
114
+ }
115
+ private:
116
+ int transfer(string word) {
117
+ int res = 0;
118
+ for (char c : word) {
119
+ res * = 10;
120
+ res += (c - 'a');
121
+ }
122
+ return res;
123
+ }
124
+ };
125
+ ```
126
+
127
127
### **...**
128
128
129
129
```
0 commit comments