英文:
while loop condtion, difference between not equal and greater than
问题
以下是您提供的内容的翻译部分:
我正在解决一个问题,即判断一个整数是否为回文数。我的逻辑是将其转换为字符串,然后设置第一个和最后一个索引。我循环遍历每个第一个和最后一个索引,如果它们是回文数,则值应该匹配。在循环中,我将第一个索引增加一,将最后一个索引减少一。所以最终它们会在中间相遇。我最初的循环条件是如果两者的索引不相同。但是这会导致字符串索引超出界限异常。但是当我将循环条件更改为只要起始小于结束就可以时,它就可以工作了。
public boolean isPalindrome(int x) {
    if(x < 0) {
        return false;
    }    	
    String val = String.valueOf(x);
    
    int end = val.length()-1;
    int start = 0;
    while(start != end) {
        if(val.charAt(start) != val.charAt(end)) {
            return false;
        }
        start++;
        end--;
    }
    
    return true;
}
}
当我执行以下操作时,它可以工作:
if(str.charAt(start++) < str.charAt(end--)) return false;
英文:
I'm doing a problem checking whether an integer is a palindrome. The logic is I convert it to string and then set the index of the first and the last. I loop through each first and last index and the values should match if they are palindrome. in the loop I increase the first index by one, I decrease the last index by one. So eventually they will meet in the half. The loop condition I originally had was if the indexes of both are not the same. but this gives me String index out of bounds exception. But then when I changed it to loop through as long as start is smaller than the end, it works.
public boolean isPalindrome(int x) {
    	if(x < 0) {
    		return false;
    	}    	
    	String val = String.valueOf(x);
    	
    	int end = val.length()-1;
    	int start = 0;
    	while(start != end) {
    		if(val.charAt(start) != val.charAt(end)) {
    			return false;
    		}
    		start++;
    		end--;
    	}
    	
    	return true;
    }
    }
it works when I do
 if(str.charAt(start++) < str.charAt(end--)) return false;
答案1
得分: 3
如果长度是偶数,就会出现问题。例如,如果长度是4,你会得到以下运行结果:
开始 | 结束
0     3
1     2
2     1
3     0
4     -1 <--- 错误
因为在整个过程中,不等式条件始终为真。
英文:
You have problem if the length is even number. For example if length is 4, you will have this run:
START | END
0     3
1     2
2     1
3     0
4     -1 <--- error
as during whole time the condition of not-equality is true.
答案2
得分: 0
问题是由于数字中的数字个数:
例如,对于 1221,start 和 end 永远不会在中间相遇:
- 迭代 1:start = 0,end = 3
 - 迭代 2:start = 1,end = 2
 - 迭代 3:start = 2,end = 1
... 
事实上,当你执行以下操作时:“它起作用”
if(str.charAt(start++) < str.charAt(end--)) return false;
纯粹是偶然。
你应该只需将 while 条件更改为:
while(start < end) {
英文:
The issue is due to the number of digit in the number :
for example, for 1221, start and end will never meet in the middle :
- iteration 1 : start = 0, end = 3
 - iteration 2 : start = 1, end = 2
 - iteration 3 : start = 2, end = 1
... 
The fact that "it works" when you do :
 if(str.charAt(start++) < str.charAt(end--)) return false;
is by chance.
You should just change the while condition to :
while(start < end) {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论