簡體   English   中英

在不轉換為字符串的情況下檢查 int 是否為回文?

[英]Checking whether an int is palindrome or not without converting into a string?

public class Palindrome {
    public static void main(String args[]) {
        int x = 121;
        int res = 0;
        while (x > 0) {
            res = res * 10 + (x % 10);
            x /= 10;
        }
        if (x - res == 0) {
            System.out.println("True" + res);
        } else
            System.out.println("False" + res);
    }
}

你好! 此代碼用於檢查整數是否為回文而不將int轉換為String 出於某種原因,計算機認為resx盡管兩者都代表數字121 提前感謝您的幫助和感謝!

你很接近。 這是一個建立在你所做的基礎上的解決方案:

static bool isPalindrome (int n1, int n2) {
    return getReverseInteger(n1) == n2;
}

static int getReverseInteger (int n) {
    int nReversed = 0;
    while (n > 0) {
      int digit = n % 10;
      nReversed = nReversed * 10 + digit;
      n = (n - digit) / 10;
    }
    return nReversed;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM