第一范文网 - 专业文章范例文档资料分享平台

JAVA经典算法50题(12)

来源:用户分享 时间:2021-06-02 本文由吃货未泯 分享 下载这篇文档 手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

public static void main(String[] args) {
Demo24 use = new Demo24();
System.out.println("请输入:");
Scanner in = new Scanner(System.in);
long a = in.nextLong();
if (a < 0 || a >= 100000) {
System.out.println("Error Input, please run this program Again!");
System.exit(0);
}
if (a >= 0 && a <= 9) {
System.out.println(a + "是一位数");
System.out.println("按逆序输出是:" + a);
} else if (a >= 10 && a <= 99) {
System.out.println(a + "是二位数");
System.out.println("按逆序输出是:");
use.converse(a);
} else if (a >= 100 && a <= 999) {
System.out.println(a + "是三位数");
System.out.println("按逆序输出是:");
use.converse(a);
} else if (a >= 1000 && a <= 9999) {
System.out.println(a + "是四位数");
System.out.println("按逆序输出是:");
use.converse(a);
} else if (a >= 10000 && a <= 99999) {
System.out.println(a + "是五位数");
System.out.println("按逆序输出是:");
use.converse(a);
}
}
public void converse(long l) {
String s = Long.toString(l);
char[] ch = s.toCharArray();
for (int i = ch.length - 1; i >= 0; i--) {
System.out.print(ch[i]);
}
}
}
个人版方法:
import java.util.Scanner;
public class Demo24 {
public static void main(String[] args) {
System.out.println("请输入:");
Scanner in = new Scanner(System.in);
String str = in.next();
if (str.matches("\\d+")) { //正则表达式
System.out.println("输入的是" + str.length() + "位数");
StringBuffer buf = new StringBuffer(str);
System.out.println(buf.reverse());//字符串反转
}
}
}

【程序25】 题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
原方法:
import java.util.Scanner;
public class Demo25 {
static int[] a = new int[5];
static int[] b = new int[5];
public static void main(String[] args) {
boolean is = false;
System.out.println("Please input:");
Scanner in = new Scanner(System.in);
long l = in.nextLong();
if (l > 99999 || l < 10000) {
System.out.println("Input error, please input again!");
l = in.nextLong();
}
for (int i = 4; i >= 0; i--) {
a[i] = (int) (l / (long) Math.pow(10, i));
l = (l % (long) Math.pow(10, i));
}
System.out.println();
for (int i = 0, j = 0; i < 5; i++, j++) {
b[j] = a[i];
}
for (int i = 0, j = 4; i < 5; i++, j--) {
if (a[i] != b[j]) {
is = false;
break;
} else {
is = true;
}
}
if (is == false) {
System.out.println("is not a Palindrom!");
} else if (is == true) {
System.out.println("is a Palindrom!");
}
}
}
个人版:
import java.util.Scanner;
public class Demo25 {
public static void main(String[]
args) {
System.out.println("请输入:");
Scanner in = new Scanner(System.in);
String str = in.next();
int l = Integer.parseInt(str);//转

搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新高等教育JAVA经典算法50题(12)全文阅读和word下载服务。

JAVA经典算法50题(12).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/wenku/1205420.html(转载请注明文章来源)
热门推荐
Copyright © 2018-2022 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top