【问题标题】:How to reverse an integer?如何反转一个整数?
【发布时间】:2021-09-06 14:39:12
【问题描述】:

我有一个反转整数的代码,但它不起作用,似乎找不到错误。

public static void test(int N) {
    int enable_print = N % 10;
    while (N > 0) {
        if (enable_print == 0 && N % 10 != 0) {
            enable_print = 1;
        } else if (enable_print == 1) {
            System.out.print(N % 10);
        }
        N = N / 10;
    }
}

【问题讨论】:

  • if替换else if
  • 不适用于输入 12345,但是如果您使用 if (enable_print >= 0) 而不是 else if 则它确实有效

标签: java debugging integer reverse


【解决方案1】:

有时重写比调试更容易和/或更好。

用伪代码编写或考虑您的算法,然后将每个高级步骤分解为更多伪代码。您的情况看起来很奇怪,因此很难调试。

最好不要将打印直接嵌入循环的中心。相反,构建一个字符串并返回它。让调用者打印一个字符串。

System.out.println (reverseInt (12345));


public static String reverseInt (anInt) {
   Initialize a StringBuffer with an empty string.
   while (anInt > 0) {
      Get last digit by modulo 10 and put in StringBuffer.
      Prepend digit in StringBuffer.
      Chop off last digit by doing integer divide.
  }
  return StringBuffer's .toString ();
}

另一种算法会递归调用 reverseInt 来构建一个不断增长的字符串。

【讨论】:

    【解决方案2】:

    if 和 else if 两者以从上到下的顺序一起工作

    if(true) { 执行 } else if() { 完成执行,即使条件为真 } else { 完成执行}

    if(false) else if(check condition) { if true 执行 else 进入下一个条件}

    等等..

    在你的情况下,这将是解决方案

    public static void test(int N) {
        int enable_print = N % 10;
        while (N > 0) {
            if (enable_print == 0 && N % 10 != 0) {
                enable_print = 1;
            }
    
            if (enable_print == 1) {
                System.out.print(N % 10);
            }
            N = N / 10;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2018-08-22
      • 2012-09-18
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多