leetcode 9。
我正在尝试将整数转换为字符串。 在子句中,在中,如果我使用
s.charat(i)== s.charat(j)
首先,然后i ++
,j -
,我无法通过输入= 121的测试,我得到了错误而不是true。但是,如果我将s.charat(i)!= s.charat(j)
首先放置,然后接受。
错误答案:
class Solution {
public boolean isPalindrome(int x) {
String s = String.valueOf(x); //n
int l = s.length();
int i = 0;
int j = l - 1;
while (i <= j) {
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
}
return false;
}
return true;
}
接受答案:
class Solution {
public boolean isPalindrome(int x) {
String s = String.valueOf(x); //n
int l = s.length();
int i = 0;
int j = l - 1;
while (i <= j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
我想念什么?
I am trying to do this converting the integer to a string.
Inside the if
clause, if I used s.charAt(i) == s.charAt(j)
first then i++
, j--
, I couldn't pass the test of input = 121, I got false instead of true. But if I put s.charAt(i) != s.charAt(j)
first, then accepted.
Wrong answer:
class Solution {
public boolean isPalindrome(int x) {
String s = String.valueOf(x); //n
int l = s.length();
int i = 0;
int j = l - 1;
while (i <= j) {
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
}
return false;
}
return true;
}
Accepted answer:
class Solution {
public boolean isPalindrome(int x) {
String s = String.valueOf(x); //n
int l = s.length();
int i = 0;
int j = l - 1;
while (i <= j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
What did I miss?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误的解决方案返回
false
在任何情况下,正确的解决方案仅返回false
s.charat(i)!= s.charat(j)
是真的。如果要跳过第一个代码中的false; 返回false; ,则您要么需要将其移至
else
条款中,或者使用继续; 在如果
子句直接跳到下一个循环迭代。The wrong solution returns
false
in any case and the correct solution only returnsfalse
whens.charAt(i) != s.charAt(j)
is true.If you want to skip
return false;
in the first code, you either need to move it into anelse
clause or usecontinue;
in theif
clause in order to directly jump to the next loop iteration.为了解决回文,更容易逆转字符串并将其与原件进行比较。
To solve a palindrome, it's easier to reverse the string and compare it with the original.