微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何反转整数?

如何解决如何反转整数?

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

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;
    }
}

解决方法

有时重写而不是调试更容易和/或更好。

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

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

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 以构建不断增长的字符串。

,

if 和 else if 都按照从上到下的顺序一起工作

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

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

等等..

就您而言,这将是解决方案

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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。