1. 程式人生 > 其它 >數字的補數

數字的補數

對整數的二進位制表示取反(0 變 1 ,1 變 0)後,再轉換為十進位制表示,可以得到這個整數的補數。

例如,整數 5 的二進位制表示是 "101" ,取反後得到 "010" ,再轉回十進位制表示得到補數 2 。
給你一個整數 num ,輸出它的補數。

 

示例 1:

輸入:num = 5
輸出:2
解釋:5 的二進位制表示為 101(沒有前導零位),其補數為 010。所以你需要輸出 2 。
示例 2:

輸入:num = 1
輸出:0
解釋:1 的二進位制表示為 1(沒有前導零位),其補數為 0。所以你需要輸出 0 。
 

提示:

1 <= num < 231

import java.util.Scanner;

public class Test { public static class ListNode{ //定義單鏈表 public int e; public ListNode next; ListNode() {} ListNode(int e) { this.e = e; } ListNode(int e, ListNode next) { this.e = e; this.next = next; } } ListNode head; int size; public void
LinkedList(){ //初始化頭結點 head = new ListNode(0 ,null); size = 0; } public void insert(int number){ //插入元素進連結串列 ListNode temp = head; // 1、先讓要新增的節點指向temp的下一個節點 ListNode newNode = new ListNode(number,temp.next); // 2、再將temp的next指向node temp.next = newNode; size
++; //連結串列長度加1 } public int re(int number){ //二進位制取反 if(number == 1){ return 0; }else { return 1; } } public static void main(String[] args) { Scanner print = new Scanner(System.in); // int i = print.nextInt(); //輸入 int j = 0,num = 0,m; int i = 2; m = i; // 儲存i值; Test test = new Test(); test.LinkedList(); if(i<0){ //判斷正負 i = -i; } while (i!=0){ j = test.re(i%2); test.insert(j); i = i/2; //重置 } ListNode p = test.head.next; //定義單鏈表頭結點下一個結點p for (int k = test.size-1; k >= 0; k--) { //求十進位制,得到補數 num += (int)Math.pow(2,k)*p.e; p = p.next; } if(m<=0){ System.out.println(-num); }else { System.out.println(num); } } }

 

 


連結:https://leetcode-cn.com/problems/number-complement
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。