A+B问题
问题描述
输入A、B,输出A+B。
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b =sc.nextInt();
System.out.println(a+b);
}
}
思路分析:
先引入一个扫描器,对创建的a,b进行扫描输入,最后再输出a+b
数列排序
问题描述
给定一个长度为n的数列,将这个数列按从小到大的顺序排列。1<=n<=200
import java.util.Arrays;
import java.util.Scanner;
public class demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
//创建数组
int[] array= new int[n];
for (int i = 0; i < n; i++) {
array[i]=sc.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; i++) {
System.out.print(array[i]+" ");
}
}
}
思路分析:
先定义一个n,用来规定这个数组中元素的个数,
用for循环再去定义一个数组包含n个整数,然后再进行排序
最后再for循环输出排序好的数组元素
3.回文数
问题描述
1221是一个非常特殊的数,它从左边读和从右边读是一样的,编程求所有这样的四位十进制数。
public class demo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 1001;i < 10000;i++){
if(i / 1000 == i % 10 && i / 100 % 10 == i / 10 % 10){
System.out.println(i);
}
}
}
}
思路分析:
直接在for循环中定义i=1001,因为是查找四位数中所有的回文数,所以i小于10000。
在循环中,如果千位上的数等于个位上的数并且,百位上的数等于十位上的数,
那么便输出这个筛选出来的数。
4.特殊回文数
问题描述
123321是一个非常特殊的数,它从左边读和从右边读是一样的。
输入一个正整数n, 编程求所有这样的五位和六位十进制数,满足各位数字之和等于n 。
package basic;
import java.util.Scanner;
public class demo4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i = 10000;i <= 999999;i++){
int sum = 0;
if(i < 100000){
if(i / 10000 != i % 10){
continue;
}
if(i / 1000 % 10 != i / 10 % 10){
continue;
}
sum = (i % 10) * 2 + (i / 10 % 10) * 2 + (i / 100 % 10);
}else{
if(i / 100000 != i % 10){
continue;
}
if(i / 10000 % 10 != i / 10 % 10){
continue;
}
if(i / 1000 % 10 != i / 100 % 10){
continue;
}
sum = (i % 10) * 2 + (i / 10 % 10) * 2 + (i / 100 % 10) * 2;
}
if(sum == n){
System.out.println(i);
}
}
}
}
思路分析:
这道题其实就是在最基本的回文数判断上延伸了下,
不仅判断是不是回文数,还要是满足每位数之和为n的特殊回文数。
我们还是用最基本的方法来求每位数,再逐一遍历一下,
最后再用if筛选出每位数之和为n的特殊回文数,输出即可
5.特殊的数字
问题描述
153是一个非常特殊的数,它等于它的每位数字的立方和,即153=1*1*1+5*5*5+3*3*3。编程求所有满足这种条件的三位十进制数。
package com.item.action;
public class demo5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 100; i < 1000; i++) {
int ge=i % 10;
int shi=i / 10 % 10;
int bai=i / 100;
if (ge*ge*ge+shi*shi*shi+bai*bai*bai==i) {
System.out.println(i+" ");
}
}
}
}
思路分析:
这道题其实也是“水仙花数”,
这三位数,其各位数字的立方和等于该数的本身。
比如:153=1的三次方+5的三次方+3的三次方
这个题的解决方法很多,比如穷举法,或者直接暴力循环。