算法是指解题方案的准确而完整的描述,是一系列解决问题的清晰指令,java算法就是采用Java语言来实现解决某一问题的清晰指令。在大家去面试的过程中,java算法也是必考的题目,所以关于java基础算法面试题大家一定要多积累!那么今天我们就来分享一下。
1. 统计一篇英文文章单词个数。public class WordCounting
{
public static void main(String[] args)
{
try (FileReader fr = new FileReader("a.txt"))
{
int counter = 0;
boolean state = false;
int currentChar;
while ((currentChar = fr.read()) != -1)
{
if (currentChar == ' ' || currentChar == '\n' ||
currentChar == '\t' || currentChar == '\r')
{
state = false;
}
else if (!state)
{
state = true;
counter++;
}
}
System.out.println(counter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
2. 输入年月日,计算该日期是这一年的第几天。public class DayCounting
{
public static void main(String[] args)
{
int[][] data = {
{
31
, 28
, 31
, 30
, 31
, 30
, 31
, 31
, 30
, 31
, 30
, 31
}
, {
31
, 29
, 31
, 30
, 31
, 30
, 31
, 31
, 30
, 31
, 30
, 31
}
};
Scanner sc = new Scanner(System.in);
System.out.print("请输入年月日(1980 11 28): ");
int year = sc.nextInt();
int month = sc.nextInt();
int date = sc.nextInt();
int[] daysOfMonth = data[(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 1 : 0];
int sum = 0;
for (int i = 0; i
{
sum += daysOfMonth[i];
}
sum += date;
System.out.println(sum);
sc.close();
}
}
3. 用递归实现字符串倒转public class StringReverse
{
public static String reverse(String originStr)
{
if (originStr == null || originStr.length() == 1)
{
return originStr;
}
return reverse(originStr.substring(1)) + originStr.charAt(0);
}
public static void main(String[] args)
{
System.out.println(reverse("hello"));
}
}
4.输入一个正整数,将其分解为素数的乘积。public class DecomposeInteger
{
private static Listlist = new ArrayList();
public static void main(String[] args)
{
System.out.print("请输入一个数: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
decomposeNumber(n);
System.out.print(n + " = ");
for (int i = 0; i
{
System.out.print(list.get(i) + " * ");
}
System.out.println(list.get(list.size() - 1));
}
public static void decomposeNumber(int n)
{
if (isPrime(n))
{
list.add(n);
list.add(1);
}
else
{
doIt(n, (int) Math.sqrt(n));
}
}
public static void doIt(int n, int div)
{
if (isPrime(div) && n % div == 0)
{
list.add(div);
decomposeNumber(n / div);
}
else
{
doIt(n, div - 1);
}
}
public static boolean isPrime(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
5. 编写一个方法求一个字符串的字节长度是多少?public int getWordCount(String s)
{
int length = 0;
for (int i = 0; i
{
int ascii = Character.codePointAt(s, i);
if (ascii >= 0 && ascii <= 255)
length++;
else
length += 2;
}
return length;
}
算法对于开发程序来说是很重要的,java人员要想成功通过面试,一定要在平时多积累面试题,掌握算法的相关知识,这样可以在面试中加分!最后大家如果想要了解更多java面试题知识,敬请关注奇Q工具网。
推荐阅读: