两道算法题

1. 字符串截取,输入为一个字符串和一个数字,但是如果遇到汉字不能只截取半个汉字。

 

package cn.lifx.test;

public class GetNBitChar 
{
	public static void main(String[] args)
	{
		String str1 = "中abc国人def伟大";
		
		GetNBitChar test = new GetNBitChar();
		
		String str2 = test.getStr(str1, 1);
		System.out.println(str2);
		
		str2 = test.getStr(str1, 4);
		System.out.println(str2);
		
		str2 = test.getStr(str1, 6);
		System.out.println(str2);
		
		str2 = test.getStr(str1, 8);
		System.out.println(str2);
		
		str2 = test.getChineseChars(str1);
		System.out.println(str2);
	}
	
	//获取前n个字节
	public String getStr(String str, int n)
	{
		String temp = "";
		
		int count = 0;
		int index = 1;
		
		while(count < n)
		{
			if(str.substring(index-1, index).getBytes().length == 1)
			{
				count++;
			}
			else
			{
				count = count + 2;
			}
			
			index++;
		}
		
		temp = str.substring(0, index-1);
		
		return temp;
	}
	
	//获得所有汉字
	public String getChineseChars(String str)
	{
		String temp = "";
		StringBuffer sb = new StringBuffer();
		
		for(int i=1; i<=str.length(); i++)
		{
			temp = str.substring(i-1, i);
			if(temp.getBytes().length == 2)
			{
				sb.append(temp);
			}
		}
		
		return sb.toString();
	}
}

 

 

2. 一个数组有2n个整数,其中有n个奇数,n个偶数,要求把奇数放在奇数位置,偶数放在偶数位置。

 

package cn.lifx.test;

public class SortOddAndEvenNum 
{
	public static void main(String[] args)
	{
		int[] arr = {2, 3, 4, 6, 8, 5, 7, 9};
		
		SortOddAndEvenNum sort = new SortOddAndEvenNum();
		
		sort.Display(arr, "Before:");
		
		sort.Sort(arr);
		
		sort.Display(arr, "After:");
	}
	
	public void Sort(int[] arr)
	{
		int index1 = 0;
		int index2 = 1;
		
		int temp = 0;
		int n = arr.length;
		
		while(index1 < n && index2 < n)
		{
			while(arr[index1] % 2 != 0)
			{
				index1 += 2;
			}
			
			while(arr[index2] % 2 == 0)
			{
				index2 += 2;
			}
			
			temp = arr[index1];
			arr[index1] = arr[index2];
			arr[index2] = temp;
			
			index1 += 2;
			index2 += 2;
		}
	}
	
	public void Display(int[] arr, String str)
	{
		System.out.println(str);
		for(int i=0; i<arr.length; i++)
		{
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}
}

  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值