華為機試題--二進位制數的每位進行0和1反轉求值
阿新 • • 發佈:2018-12-27
一、問題描述
功能描述:對一個二進位制數的每位進行0和1反轉,求翻轉後的二進位制所對應的十進位制
輸入:110
輸出:1
要求實現方法:
public String getNumber(BigInteger data)
{
//TODO
return "";
}
二、演算法
public String getNumber(BigInteger data) { String biStr = String.valueOf(data); char[] arr = biStr.toCharArray(); for (int i = 0; i < arr.length; i++) { if (arr[i] == '0') { arr[i] = '1'; } else { arr[i] = '0'; } } //reverse. int result = 0; for (int i = 0; i < arr.length; i++) { int temp = 1; int isum = 0; if(Character.getNumericValue(arr[i]) != 0) { if(i == arr.length -1 ) { result += 1;// 2的零字幕 = 1 continue; } while (temp <= i) { isum = temp * 2; temp ++; } } result += isum; } return String.valueOf(result); }
三、測試方法
package com.albertshao.csi.interview; import java.math.BigInteger; /** * @author albertshao */ public class Main17 { public static void main(String[] args) { Main17 m = new Main17(); System.out.println(m.getNumber(new BigInteger("110"))); } public String getNumber(BigInteger data) { String biStr = String.valueOf(data); char[] arr = biStr.toCharArray(); for (int i = 0; i < arr.length; i++) { if (arr[i] == '0') { arr[i] = '1'; } else { arr[i] = '0'; } } //reverse. int result = 0; for (int i = 0; i < arr.length; i++) { int temp = 1; int isum = 0; if(Character.getNumericValue(arr[i]) != 0) { if(i == arr.length -1 ) { result += 1;// 2的零字幕 = 1 continue; } while (temp <= i) { isum = temp * 2; temp ++; } } result += isum; } return String.valueOf(result); } }
執行結果
1