import java.util.*;
public class Postfix{
public static int priority(String str){
switch( str ){
case "+": case "-":
return 1;
case "*": case"/": case "%":
return 2;
default:
return 0;
}
}
public static String toPostfix(String str){
StringBuffer sb = new StringBuffer();
LinkedList<String> stack = new LinkedList<String>();
for(String sub : str.split(" ") ){
if("(".indexOf(sub) != -1){
stack.add(sub);
}else if("+-*/%".indexOf(sub) != -1){
while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
sb.append(stack.removeLast() + " ");
}
stack.add(sub);
}else if(")".indexOf(sub) != -1){
while( "(".indexOf(stack.getLast()) == -1 ){
sb.append(stack.removeLast() + " ");
}
stack.removeLast();
}else{
sb.append(sub + " ");
}
}
while(!stack.isEmpty()){ sb.append(stack.removeLast()); }
return sb.toString();
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
System.out.println( toPostfix(str) );
}
}
}
參考:良葛格學習筆記
2012年5月19日 星期六
Java 中序式轉後序式
2012年5月13日 星期日
Java 大數運算
import java.util.*;
import java.math.*;
public class BigNumberCount{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
StringBuffer sb = new StringBuffer(str);
String str1 = sb.substring(0, sb.indexOf(" "));
sb.delete(0, sb.indexOf(" ")+1);
String symbol = sb.substring(0, sb.indexOf(" "));
String str2 = sb.substring(sb.indexOf(" ")+1, sb.length());
BigInteger a = new BigInteger(str1);
BigInteger b = new BigInteger(str2);
switch( symbol.charAt(0) ){
case '+':
System.out.println( a.add(b) );
break;
case '-':
System.out.println( a.subtract(b) );
break;
case '*':
System.out.println( a.multiply(b) );
break;
case '/':
System.out.println( a.divide(b) );
break;
}
}
}
}
說明
直接使用Java.math底下的BigInteger類別實做題目
大數運算參考
超長整數運算(大數運算)2012年5月12日 星期六
2012年4月13日 星期五
Java 迴文
import java.util.Scanner;
public class Palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
String tmp = "";
int length = str.length() - 1;
for(int i = length; i >= 0; i--){
tmp += str.charAt(i);
}
if( str.equals(tmp) ){
System.out.println("yes");
}
else{
System.out.println("no");
}
}
}
}
題目
參考程式
2012年4月12日 星期四
Java 阿姆斯壯數
import java.util.Scanner;
public class ArmstrongNumber{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a,b;
while( sc.hasNext() ){
a = sc.nextInt();
b = sc.nextInt();
int count = 0;
for(int i = a; i <= b; i++){
boolean ans = false;
int length = String.valueOf(i).length();
int sum = 0;
switch( length ){
case 7:
sum += Math.pow(i/1000000,length);
case 6:
sum += Math.pow((i%1000000)/100000,length);
case 5:
sum += Math.pow((i%100000)/10000,length);
case 4:
sum += Math.pow((i%10000)/1000,length);
case 3:
sum += Math.pow((i%1000)/100,length);
case 2:
sum += Math.pow((i%100)/10,length);
case 1:
sum += Math.pow(i%10,length);
break;
}
if( sum == i ){
System.out.print( i + " ");
count++;
}
}
if( count != 0 ){
System.out.println();
}
else{
System.out.println("none");
}
}
}
}
題目
Java 數字翻轉
import java.util.Scanner;
public class NumberTurn{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
char c [] = str.toCharArray();
String tmp = "";
for( int i = c.length - 1; i >= 0; i-- ){
tmp += c[i];
}
System.out.println( Integer.parseInt(tmp) );
}
}
}
題目
參考程式
Java 二進位轉換
import java.util.Scanner;
public class CarryTransform{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;
while( sc.hasNext() ){
num = sc.nextInt();
System.out.println( Integer.toBinaryString(num) );
}
}
}
題目
Java 最大公因數
import java.util.Scanner;
public class GCD{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a,b;
while( sc.hasNext() ){
a = sc.nextInt();
b = sc.nextInt();
int i = 0;
while( b != 0 ){
i = a % b;
a = b;
b = i;
}
System.out.println( a );
}
}
}
題目
2012年4月9日 星期一
Java 身分證檢驗
import java.util.Scanner;
public class IdAuthentication{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str;
while( sc.hasNext() ){
str = sc.nextLine();
char c [] = str.toCharArray();
if( c[0] == 88 || c[0] == 89 ){
c[0] -= 58;
}
else if( c[0] >= 65 && c[0] <= 72 ){
c[0] -= 55;
}else if( c[0] >= 74 && c[0] <= 78){
c[0] -= 56;
}else if( c[0] >= 80 && c[0] <= 86){
c[0] -= 57;
}else{
c[0] = (c[0] == 73) ? 34 : (c[0] == 79) ? 35 :
(c[0] == 87) ? 32 : (c[0] == 90) ? 33 : c[0];
}
int sum = c[0]/10 + (c[0]%10)*9 + (c[9]-48);
for(int i = 1; i < c.length-1; i++){
sum += (c[i]-48)*(9-i);
}
if( sum % 10 == 0 ){
System.out.println("real");
}
else{
System.out.println("fake");
}
}
}
}
題目
2012年4月6日 星期五
Java 數獨判斷
import java.util.Scanner;
public class Sudoku{
public static int array [][] = new int [9][9];
public static boolean checkRow(int row){
int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[row][i];
}
if( sum < 45 || sum > 45 ){
return false;
}
return true;
}
public static boolean checkColumn(int column){
int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i][column];
}
if( sum < 45 || sum > 45 ){
return false;
}
return true;
}
public static boolean checkLittlePalaceGrid(int box){
int sum = 0;
int row = (box / 3) * 3;
int column = (box < 3) ? box*3 : (box < 6) ? (box - 3)*3 : (box - 6)*3;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
sum += array[i + row][j + column];
}
}
if( sum < 45 || sum > 45 ){
return false;
}
return true;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
boolean row=true,column=true,lpg=true;
while( sc.hasNext() ){
for(int j = 0; j < 9; j++ ){
int a [] = {0,0,0,0,0,0,0,0,0};
for(int k = 0; k < 9; k++){
a[k] = sc.nextInt();
}
array[j] = a;
}
int i = 0;
while(i < array.length){
row = checkRow(i);
column = checkColumn(i);
lpg = checkLittlePalaceGrid(i);
if(row == false || column == false || lpg == false){
System.out.println("no");
break;
}
if( i == array.length - 1 ){
System.out.println("yes");
}
i++;
}
}
}
}
題目
2012年4月4日 星期三
Java 矩陣翻轉
import java.util.Scanner;
public class Matrix{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int row,colum;
int matrix [][];
while(sc.hasNext()){
row = sc.nextInt();
colum = sc.nextInt();
matrix = new int [row][colum];
for( int i = 0; i < row; i++ ){
for( int j = 0; j < colum; j++){
matrix[i][j] = sc.nextInt();
}
}
for( int i = 0; i < colum; i++ ){
for( int j = 0; j < row; j++){
System.out.print(matrix[j][i] + " ");
}
System.out.println();
}
}
}
}
題目
2012年3月19日 星期一
Eclipse無法Debug
最近又開始玩android
當要debug的時候竟然出現錯誤
訊息"Error generating final archive: Debug Certificate expired on....."
原因不明,所以就google一下
原來是憑證到期了
解法如下:
第一步: 把"C:\Documents and Settings\user\.android"裡的debug.keystore檔刪除
第二步: 點開時間與日期內容,選時區
第三步: 更新時間,後按確定
第四步: 在eclipse重新建一個專案
第五步: 直接debug讓它重新建置 debug.keystore檔
這樣就OK囉!
參考文章
當要debug的時候竟然出現錯誤
訊息"Error generating final archive: Debug Certificate expired on....."
原因不明,所以就google一下
原來是憑證到期了
解法如下:
第一步: 把"C:\Documents and Settings\user\.android"裡的debug.keystore檔刪除
第二步: 點開時間與日期內容,選時區
第三步: 更新時間,後按確定
第四步: 在eclipse重新建一個專案
第五步: 直接debug讓它重新建置 debug.keystore檔
這樣就OK囉!
參考文章
2012年3月9日 星期五
2012年3月8日 星期四
2012年3月5日 星期一
Java 羅馬數字
import java.util.*;
public class RomeNumber{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str [] = sc.nextLine().split(" ");
if(str[0].equals("#")){
break;
}
int a = transformIntNumber(str[0]);
int b = transformIntNumber(str[1]);
int sum = Math.abs(a - b);
if( sum == 0){
System.out.println("ZERO");
}
else{
System.out.println(transformRomeNumber(sum));
}
}
}
public static int transformIntNumber(String s){
int count = 0;
int a [] = new int [s.length()];
for(int i = 0; i < a.length; i++){
switch(s.charAt(i)){
case 'I':
a[i] = 1;
break;
case 'V':
a[i] = 5;
break;
case 'X':
a[i] = 10;
break;
case 'L':
a[i] = 50;
break;
case 'C':
a[i] = 100;
break;
case 'D':
a[i] = 500;
break;
case 'M':
a[i] = 1000;
break;
}
}
for(int i = 0; i < a.length; i++){
if( i == (a.length - 1)){
count += a[i];
break;
}
else if( a[i] < a[i+1] ){
count -= a[i];
}
else{
count += a[i];
}
}
return count;
}
public static String transformRomeNumber(int a){
String str = "";
int index;
String rome [] = {"I","V","X","L","C","D","M"};
int num [] = {1,5,10,50,100,500,1000};
Arrays.sort(num);
while( a > 0 ){
index = Arrays.binarySearch(num, a);
if(index == -8){
index = 6;
}else if(index < 0){
index = -1 * index -2;
int i = index / 2 * 2;
if(a + num[i] >= num[index + 1]){
str += rome[i];
a += num[i];
index++;
}
}
str += rome[index];
a -= num[index];
}
return str;
}
}
題目
參考程式
2011年10月24日 星期一
驗證圖形驗證碼
index.jsp ----->主頁面
Verification.jsp ----->驗證
DynamicImage.java ---->產生動態圖形驗證碼
web.xml
<%@ page language="java" contentType="text/html; charset=BIG5"%>
<form method="post" action="Verification.jsp">
<img src="dynamicImage"/><br/>
<input type="text" name="value"></input>
<input type="submit"></input>
</form>
Verification.jsp ----->驗證
<%@ page language="java" contentType="text/html; charset=big5"%>
<%
if( request.getParameter("value").equals(session.getAttribute("number")) ){
out.print("驗證碼正確");
}else{
out.print("驗證碼錯誤");
}
%>
DynamicImage.java ---->產生動態圖形驗證碼
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DynamicImage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
response.setContentType("image/jpeg");
BufferedImage bi = new BufferedImage(50,30,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, 50, 30);
g2d.setColor(Color.black);
g2d.drawRect(5, 5, 40, 20);
StringBuilder sbl = new StringBuilder();
while(sbl.length() < 4){
sbl.append(Integer.toString((int)(Math.random() * 9)));
}
session.setAttribute("number", sbl.toString());
g2d.setFont(new Font("Default",Font.BOLD,13));
g2d.drawString(sbl.toString(), 10, 20);
for(int i = 0; i < 20; i++){
int x = (int)(Math.random() * 40) + 5;
int y = (int)(Math.random() * 20) + 5;
g2d.fillOval(x, y, 1, 1);
}
ServletOutputStream sos = response.getOutputStream();
Iterator ite = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter iw = (ImageWriter)ite.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(sos);
iw.setOutput(ios);
iw.write(bi);
ios.flush();
sos.close();
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DynamicImage</servlet-name>
<servlet-class>com.morty.dynamicimage.DynamicImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DynamicImage</servlet-name>
<url-pattern>/dynamicImage</url-pattern>
</servlet-mapping>
</web-app>
2011年10月23日 星期日
動態產生密碼圖片
DynamicImage.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DynamicImage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage bi = new BufferedImage(50,30,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, 50, 30);
g2d.setColor(Color.black);
g2d.drawRect(5, 5, 40, 20);
StringBuilder sbl = new StringBuilder();
while(sbl.length() < 4){
sbl.append(Integer.toString((int)(Math.random() * 9)));
}
g2d.setFont(new Font("Default",Font.BOLD,13));
g2d.drawString(sbl.toString(), 10, 20);
for(int i = 0; i < 20; i++){
int x = (int)(Math.random() * 40) + 5;
int y = (int)(Math.random() * 20) + 5;
g2d.fillOval(x, y, 1, 1);
}
response.setContentType("image/jpeg");
ServletOutputStream sos = response.getOutputStream();
Iterator ite = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter iw = (ImageWriter)ite.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(sos);
iw.setOutput(ios);
iw.write(bi);
ios.flush();
sos.close();
}
}
2011年10月3日 星期一
BMI指數
BMI.jsp
<%@ page contentType="text/html; charset=big5"%>
<form method="post" action="BMI.jsp">
性別:<select name="sex">
<option></option>
<option value="man">男</option>
<option value="woman">女</option>
</select><br>
身高(公分):<input type="text" name="height" style="width:5%"/><br>
體重(公斤):<input type="text" name="weight" style="width:5%"/><br>
<input type="submit" value="送出">
</form>
<%
String height = request.getParameter("height");
String weight = request.getParameter("weight");
if(height == null || weight == null){
height = "0.0";
weight = "0.0";
}
String url = "count.jsp?height=" + height + "&weight=" + weight;
%>
<jsp:include page="<%=url%>"></jsp:include>
count.jsp
<%@ page contentType="text/html; charset=big5" %>
<%@
page import="java.io.*"
%>
<%
String exponent = "";
String standard = "";
int num = 0;
double h=0.0,w=0.0;
h = Double.parseDouble(request.getParameter("height")) / 100;
w = Double.parseDouble(request.getParameter("weight"));
double ans = w / (Math.pow(h, 2)); //體重 (kg) / 身高 (m)的平方
if( Double.isNaN(ans) == false){
exponent = Long.toString(Math.round(ans));
num = Integer.parseInt(exponent);
/*
男性: (身高cm-80)×70﹪=標準體重
女性: (身高cm-70)×60﹪=標準體重
*/
if(request.getParameter("sex").equals("man")){
standard = Double.toString(((h*100)-80)*0.7) + " 公斤";
}else{
standard = Double.toString(((h*100)-70)*0.6) + " 公斤";
}
}
String str = "";
//結果
if( num == 0){
str = "";
}else if( num < 18.5 ){
str = "體重過輕";
}else if( num > 18.5 && num < 24){
str = "正常範圍";
}else if( num >= 24 && num < 27){
str = "體重過重";
}else if( num >= 27 && num < 30){
str = "輕度肥胖";
}else if( num >= 30 && num < 35 ){
str = "中度肥胖";
}else{
str = "重度肥胖";
}
%>
<p>BMI 指數:<%=exponent%></p>
<p>結果:<%=str%></p>
<p>標準體重:<%=standard%></p>
web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<welcome-file-list>
<welcome-file>BMI.jsp</welcome-file>
</welcome-file-list>
</web-app>
2011年6月6日 星期一
Java LCS 最長共同子序列
import java.util.Scanner;
public class LongComSub {
public static String str1;
public static String str2;
public static String result;//記錄共同子序列
public static char [] cha1;
public static char [] cha2;
public static int [][] array;//LCS表格
public static String [][] prev;//記錄計算方向
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("輸入第一個字串: ");
str1 = sc.nextLine();
System.out.print("輸入第二個字串: ");
str2 = sc.nextLine();
/*str1為短字串 str2為長字串*/
if(str1.length() > str2.length()){
String value = str1;
str1 = "0" + str2;
str2 = "0" + value;
}
else{
str1 = "0" + str1;
str2 = "0" + str2;
}
/*設定陣列長度*/
array = new int[str1.length()][str2.length()];
prev = new String[str1.length()][str2.length()];
/*將字串轉換為陣列*/
cha1 = str1.toCharArray();
cha2 = str2.toCharArray();
setZero();
countLCS();
foundValue(cha1.length-1,cha2.length-1);
System.out.print("最長共同子序列: ");
StringBuffer sb = new StringBuffer(result.substring(4));
System.out.print(sb.reverse());
}
/*將 array[x][0] 和 array[0][x] 都設為 0*/
public static void setZero(){
for(int i = 0; i < str1.length(); i++){
array[i][0] = 0;
}
for(int i = 0; i < str2.length(); i++){
array[0][i] = 0;
}
}
/*計算並製作LCS表格*/
public static void countLCS(){
System.out.print(" ");
for(int u = 0; u < cha2.length; u++){
System.out.print(cha2[u] + " ");
}
System.out.println();
for(int i = 1; i < cha1.length; i++){
System.out.print(cha1[i] + " ");
for(int j = 1; j < cha2.length; j++){
if( i == 0 || j == 0 ){
System.out.print(array[i][j] + " ");
continue;
}
if( cha1[i] == cha2[j] ){
array[i][j] = array[i-1][j-1] + 1;
prev[i][j] = "左上方";
System.out.print(array[i][j] + " ");
}
else if( array[i-1][j] < array[i][j-1]){
array[i][j] = array[i][j-1];
prev[i][j] = "左方";
System.out.print(array[i][j] + " ");
}
else{
array[i][j] = array[i-1][j];
prev[i][j] = "上方";
System.out.print(array[i][j] + " ");
}
}
}
}
/*找出LCS值*/
public static void foundValue(int a,int b){
if(a == 0 && b == 0){
System.exit(0);
}
if(prev[a][b] == "左上方"){
//String初始值null,所以會從null開使加字串
result += Character.toString(cha1[a]);
foundValue(a-1,b-1);
}
else if(prev[a][b] == "上方"){
foundValue(a-1,b);
}
else if(prev[a][b] == "左方"){
foundValue(a,b-1);
}
}
}
沒有考慮到時間複雜度以及記憶體問題唷
2011年5月26日 星期四
Java 偶基數判斷
一般的比較法
較快速的比較法
3 & 1 = 0011 & 0001 = 1
4 & 1 = 0100 & 0001 = 0
用%的話就顯得比&還要慢了
來源
int a = 3;
int b = 4;
System.out.println(a%2==0?"a是偶數":"a是奇數");
System.out.println(b%2==0?"b是偶數":"b是奇數");
較快速的比較法
int a = 3;
int b = 4;
System.out.println((a&1)==0?"a是偶數":"a是奇數");
System.out.println((b&1)==0?"b是偶數":"b是奇數");
3 & 1 = 0011 & 0001 = 1
4 & 1 = 0100 & 0001 = 0
用%的話就顯得比&還要慢了
來源
訂閱:
文章 (Atom)